【问题标题】:How to define alternating elements in XML with XSD如何使用 XSD 在 XML 中定义交替元素
【发布时间】:2023-03-29 17:15:01
【问题描述】:

我想在我的 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/>

其中 customercustomerContact 不会交替出现。我的想法是定义一个元素,上面写着 customer or customerContact 并允许重复该元素。这将解决我的问题,但它也将允许其他不应被接受为有效的解决方案。

我认为干净的解决方案是使用类似 XML

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

并重复 customerEnvelope。不幸的是,我的客户已经给出了 XML 结构,所以我无法在此处进行更改。

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

【问题讨论】:

    标签: xml xsd


    【解决方案1】:
    <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>
    

    【讨论】:

    • 这是一个非常简单的解决方案 - 有时最明显的事情是最困难的。非常感谢@13ren!
    • @MathiasBader 谢谢,XSD 在某些方面相当不错。顺便说一句:你可以把它想象成正则表达式ab(cd)*
    猜你喜欢
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多