XML模式1.0沒有直接解決您的問題。
你想要什麼,是以下(更換xs:sequence
與xs:all
),但這不是有效的XML Schema語言:
<xs:complexType name="parent">
<xs:choice>
<xs:all>
<xs:element name="child1" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<xs:element name="child2" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<!-- ... -->
</xs:all>
<xs:all>
<xs:element name="child11" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<xs:element name="child12" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<!-- ... -->
</xs:all>
</xs:choice>
</xs:complexType>
的問題是,xs:choice
允許xs:sequence
嵌套和xs:choice
合成器,但不是xs:all
。
有五種可能性我看:
- 使用模式在你的問題,它採用
xs:sequence
代替xs:all
,但使用XSL轉換驗證之前重新排序按照模式。
- 如果XML Schema 1.1是一個選項,您可以定義一個更寬鬆的模式(即不強制執行所有規則但接受所有有效輸入的模式),但可以使用
xs:assert
進行額外的檢查。
- 或者定義一個更寬鬆的模式,但在模式驗證步驟之後,在自己的程序中執行額外的檢查。
- 重構模式,以便兩組相關元素嵌套在另一個元素下,以便您可以使用
xs:choice
。
- 將抽象類型定義爲
parent
,爲內容模型的兩種選擇定義派生類型,並使用xsi:type
指定在XML文檔中使用哪一種。
後兩種選擇都需要不幸地改變XML格式。
這是你的架構會如何看,如果你可以添加一個額外級別的元素嵌套:
<xs:complexType name="option1">
<xs:all>
<xs:element name="child1" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<xs:element name="child2" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<!-- ... -->
</xs:all>
</xs:complexType>
<xs:complexType name="option2">
<xs:all>
<xs:element name="child11" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<xs:element name="child12" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<!-- ... -->
</xs:all>
</xs:complexType>
<xs:complexType name="parent">
<xs:choice>
<xs:element name="option1" type="option1"/>
<xs:element name="option2" type="option2"/>
</xs:choice>
</xs:complexType>
這是如果你使用類型替換您的架構可能的樣子:
<xs:complexType name="parent" abstract="true">
</xs:complexType>
<xs:complexType name="parent_option1">
<xs:complexContent>
<xs:extension base="parent">
<xs:all>
<xs:element name="child1" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<xs:element name="child2" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<!-- ... -->
</xs:all>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="parent_option2">
<xs:complexContent>
<xs:extension base="parent">
<xs:all>
<xs:element name="child11" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<xs:element name="child12" type="xs:integer" minOccurs="1" maxOccurs="1"/>
<!-- ... -->
</xs:all>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:element name="parent" type="parent"/>
使用此方法的XML實例文檔看起來像下面的第一組el對此語句(請注意使用的xsi:type
指定哪些組已經被選中):
<parent
xmlns="Your namespace here"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="parent_option1">
<child2>2</child2>
<child1>1</child1>
<!-- ... -->
</parent>
而對於第二組:
<parent
xmlns="Your namespace here"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="parent_option2">
<child11>11</child11>
<child12>12</child12>
<!-- ... -->
</parent>
爲什麼'child1'不能與'child11'(實施例4)然而'child5'可以用'child20'(例子2)? – kjhughes 2015-04-04 19:11:51
@kjhughes好點我沒有注意到,我認爲這是一個錯字 – softwariness 2015-04-04 19:23:51
是的,很抱歉,它現在解決了 – 2015-04-04 22:27:35