2010-06-27 37 views
2

我正在使用XSD。我想要一個container元素(複合類型),其中包含任何基本類型爲component的元素。xsd中的抽象

一種方法是...

<complexType name="Container"> 
    <sequence> 
     <element name="Child" type="am:Component"></element> 
    </sequence> 
</complexType> 

但問題還有我的組件被稱爲兒童。假設我有3個組件,foobarbaz。我希望能做出一個看起來像一個文件...

<container> 
    <foo fooTag="foo"/> 
    <foo fooTag="foo"/> 
    <baz bazTag="baz"/> 
    <bar barTag="bar"/> 
</container> 

隨着我結束了第一種方法......

<container> 
    <child fooTag="foo"/> 
    <child fooTag="foo"/> 
    <child bazTag="baz"/> 
    <child barTag="bar"/> 
</container> 

我可以簡單地使用xs:any元素,但我會失去我的斷言,孩子必須是component。有什麼方法可以得到我想要的嗎?

回答

2

最終,您需要能夠說「類型Foo是由名爲foo的元素表示的」,這就是xs:元素的名稱屬性。你不能做徹底的抽象(就像你在編程語言中那樣),因爲類型只是定義,並沒有一個特定的元素名稱,除非你給它一個。

您需要列出序列中的每個可能的子類型。

<xs:sequence> 
    <xs:choice> 
     <xs:element name="type1" type="Type1" /> 
     <xs:element name="type2" type="Type2" /> 
     <xs:element name="type3" type="Type3" /> 
     <xs:element name="type4" type="Type4" /> 
    </xs:choice> 
</xs:sequence> 

也可以全局定義的元素名稱,並指他們像這樣,但最終你還是要指出哪些子元素名稱是您的容器元素內有效。

<xs:sequence> 
    <xs:any> 
     <xs:element ref="type1" /> 
     <xs:element ref="type2" /> 
     <xs:element ref="type3" /> 
     <xs:element ref="type4" /> 
    </xs:any> 
</xs:sequence> 

和其他地方:

<xs:element name="type1" type="Type1" /> 
<xs:element name="type2" type="Type2" /> 
<xs:element name="type3" type="Type3" /> 
<xs:element name="type4" type="Type4" /> 
+0

我怕的就是這個。感謝您的好回答和例子。 – Pace 2010-06-27 03:34:18

+0

是的......不幸的是,對於任何來自編程觀點的人來說,這種行爲都是違反直覺的。儘管這種限制在.NET Web服務中有所體現 - 例如WSDL生成器不夠聰明,無法處理子類型,除非您明確告訴它哪些子類型是有效的(通過XmlIncludeAttribute)。 – 2010-06-27 03:37:27