如何使用XSD在XML中定义交替元素

时间:2013-01-22 10:17:53

标签: xml xsd

我想在我的XSD文件中定义两个可以在很多时间内发生'无界'的元素,但它们必须一个接一个地来。例如:

XML的文件:

<company/>
<address/>
<customer/>
<customerContact/>
<customer/>
<customerContact/>
<customer/>
<customerContact/>

现在的问题是,以下XSD定义

<xs:element name="company" type="companyType"/>
<xs:element name="address" type="addressType"/>
<xs:element name="customer" type="customerType" maxOccurs="unbounded"/>
<xs:element name="customerContact" type="customerContactType" maxOccurs="unbounded"/>

仅适用于

等XML文件
<company/>
<address/>
<customer/>
<customer/>
<customer/>
<customerContact/>
<customerContact/>
<customerContact/>

其中客户 customerContact 不会替代。我有想法定义一个元素,其中包含 customer customerContact ,并允许重复该元素。这样可以解决我的问题,但它也会允许其他不应被视为有效的解决方案。

我认为干净的解决方案就是拥有像

这样的XML
<company/>
<address/>
<customerEnvelope>
    <customer/>
    <customerContact/>
<customerEnvelope>
<customerEnvelope>
    <customer/>
    <customerContact/>
</customerEnvelope>

并重复 customerEnvelope 。不幸的是,我的客户已经提供了XML结构,因此我无法在此进行更改。

是否可以使用XSD定义这种结构,还是需要使用上述解决方法?

1 个答案:

答案 0 :(得分:3)

<xs:element name="company" type="companyType"/>
<xs:element name="address" type="addressType"/>
<xs:sequence maxOccurs="unbounded">
  <xs:element name="customer" type="customerType"/>
  <xs:element name="customerContact" type="customerContactType"/>
</xs:sequence>