2015-12-04 71 views
1

我有一个XSD元素一个值,XSI XSD元素:无= “真”

<xsd:element name="author" type="cmd:Author" nillable="true"> 
    <xsd:annotation> 
     <xsd:documentation>Contains author name and author id 
     </xsd:documentation> 
    </xsd:annotation> 
</xsd:element> 

类型作者:

<xsd:complexType name="Author"> 
    <xsd:annotation> 
     <xsd:documentation>Author's name and id. 
     </xsd:documentation> 
    </xsd:annotation> 
    <xsd:simpleContent> 
     <xsd:extension base="cmd:AuthorName"> 
      <xsd:attribute name="id" type="cmd:Id" use="optional"> 
       <xsd:annotation> 
        <xsd:documentation>Author's Id 
        </xsd:documentation> 
       </xsd:annotation> 
      </xsd:attribute> 
     </xsd:extension> 
    </xsd:simpleContent> 
</xsd:complexType> 

基地AUTHORNAME:

<xsd:simpleType name="AuthorName"> 
    <xsd:annotation> 
     <xsd:documentation>Type defining author's name. 
       It may contain characters from AllowedChars 
     </xsd:documentation> 
    </xsd:annotation> 
    <xsd:restriction base="cmd:AllowedChars"> 
     <xsd:maxLength value="112"/> 
    </xsd:restriction> 
</xsd:simpleType> 

类型标识:

<xsd:simpleType name="Id"> 
    <xsd:annotation> 
     <xsd:documentation>Id 
     </xsd:documentation> 
    </xsd:annotation> 
    <xsd:restriction base="xsd:string"> 
     <xsd:pattern value="\d{6}"/> 
    </xsd:restriction> 
</xsd:simpleType> 

问题是我总是有一个ID,但有时可能发生AuthorName为空。

在那种情况下我得到的是:

<author id="111111"/> 

我想要得到的是:

<author id="111111" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:nil="true"/> 

我的实际情况,使问题与架构的兼容性。在不改变XSD模型的情况下可以做我想要的东西吗?将Author拆分为AuthorName和AuthorId不是向后兼容的,并且需要重写相当大的应用程序。其他信息(我不太清楚什么是有用的,什么不是): 应用程序在J2E中,我使用JAXB绑定xsd,并且使用XJC生成类。

生成的类作者:

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(name = "Author", propOrder = { 
    "value" 
}) 
public class Author implements Serializable 
{ 
    @XmlValue 
    protected String value; 
    @XmlAttribute(name = "id") 
    protected String id; 
    //getters and setters 
} 

回答

1

您可能需要提供有关执行情况以及信息;最有可能的是,这是限制你得到你所需要的。

明智地说,你是对的。在声明其他XML属性可能出现在其xsi:nil属性已设置为true的元素中时(重点是我的),XSD规范很明确。

如果元素的属性为xsi:nil且值为true,则该元素可能是有效的无内容。如此标记的元素必须为空,,但如果相应的复合类型允许,则可以携带属性

问题是大多数绑定技术还没有实现这种行为。例如,MSDN上的this article明确表明您的方案不受其标准XML序列化程序支持。这是一个摘录:

  • 当反序列化XML文档转换为对象:如果的XmlSerializer类遇到一个指定的xsi XML元素:无=“真”时,它分配一个空引用到相应的对象并忽略任何其他属性。如果XML文档是通过允许其他属性与xsi一起出现的XML模式实现创建的,则会出现这种情况:nil =“true” - 实际上不会将空值对象引用的真值绑定到无效

相反,它会无法正常工作的其他方式,即如果任何其他属性设置,这将不能够序列化XSI:无=“true”属性。

如果你正在内部进行此操作,可能会有方法来调整序列化器以便按照你想要的方式工作 - 同样,你需要提供更多信息。否则,正如我上面所显示的那样,您应该假设有一些平台可能无法正常工作(开箱即用)。