XML Schema结合了“choice”和“all”

时间:2013-09-17 14:30:31

标签: xml xsd

我正在尝试编写一个XSD来验证XML,其中必须满足以下条件:

元素(Parent)包括:

  • “Choice1”或“Choice2”元素
  • 加上任何或所有“Field1”,“Field2”,“Field2”(等等)
  • 以上字段可以按任何顺序出现

因此,例如,有效的XML将是:

<Parent>
  <Choice1>xxx</Choice1>
  <Field1>yyy</Field1>
  <Field2>yyy</Field2>
</Parent>

就像:

<Parent>
  <Field3>yyy</Field3>
  <Choice2>xxx</Choice2>
  <Field2>yyy</Field2>
</Parent>

无效将是:

<Parent>
  <Field3>yyy</Field3>
  <Field2>yyy</Field2>
</Parent>

我似乎无法按照我的意愿嵌套xs:choice和xs:all。

1 个答案:

答案 0 :(得分:2)

是的,<xs:choice>无法直接插入<xs:all>。 但是使用替换组可以达到相同的效果:

<xs:element name="Parent">
  <xs:complexType>
    <xs:all>
      <xs:element ref="Choice" minOccurs="1"/>

      <xs:element name="Field1" type="xs:string"/>
      <xs:element name="Field2" type="xs:string"/>
    </xs:all>
  </xs:complexType>
</xs:element>

<xs:element name="Choice" abstract="true"/>
<xs:element name="Choice1" substitutionGroup="Choice"> ... </xs:element>
<xs:element name="Choice2" substitutionGroup="Choice"> ... </xs:element>