2015-12-04 32 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」屬性。

如果你正在內部進行此操作,可能會有方法來調整序列化器以便按照你想要的方式工作 - 同樣,你需要提供更多信息。否則,正如我上面所顯示的那樣,您應該假設有一些平臺可能無法正常工作(開箱即用)。