【问题标题】:How to make one of two optional tag dependent on the other?如何使两个可选标签之一依赖于另一个?
【发布时间】:2015-07-21 19:20:58
【问题描述】:

我在 XSD 中有两个标签:

<xsd:element name="tag1" minOccurs="0">

<xsd:element name="tag2" minOccurs="0">

它们都是可选的,可以省略。但是我想添加一个限制,如果给出了 tag2,也应该给出 tag1(因为 tag2 依赖于 tag1)。如何仅通过 XSD 实现这一目标?


编辑:

它们之间有强制标签。因此,序列将不起作用。例如

<xsd:element name="tag1" minOccurs="0">
<xsd:element name="tag3" minOccurs="1">
<xsd:element name="tag4" minOccurs="1">
<xsd:element name="tag2" minOccurs="0">

【问题讨论】:

    标签: xml xsd


    【解决方案1】:

    这里有一些解决方案:

    使用选择

    这是一个很长的解决方案,因为它重复了模型的某些部分,但如果您确实需要可选标签之间的强制标签并且标签不在xs:all 内,它就可以工作:

    <xsd:choice>
    
        <!-- Choice option 1: optional tags present -->
        <xsd:sequence>
            <xsd:element name="optionalTag1"/>
            <xsd:element name="complulsoryTag1"/>
            <xsd:element name="complulsoryTag2"/>
            <xsd:element name="optionalTag2"/>
        </xsd:sequence>
    
        <!-- Choice option 2: optional tags not present -->
        <xsd:sequence>
            <xsd:element name="complulsoryTag1"/>
            <xsd:element name="complulsoryTag2"/>
        </xsd:sequence>
    
    </xsd:choice>
    

    请注意,如果您使用xs:group 对您的complusory 中心标签进行分组,您可以避免在模型上重复标签。

    以可选顺序包装标签

    如果它们之间没有强制标签,您可以简单地将它们包装成带有minOccurs=0 的序列。因此,如果序列出现,则两个标签都存在,如果序列没有出现,则没有任何标签存在:

    <xsd:sequence minOccurs="0">
        <xsd:element name="tag1"/>
        <xsd:element name="tag2"/>
    </xsd:sequence>
    

    请注意,这在 xs:all 中不起作用,但您可以在选择中使用它,如果需要,甚至可以在另一个序列中使用它。

    使用 XSD 1.1 断言

    如果您的处理器使用 XSD 1.1,您可以使用 xs:assert 确保所有可选标签都存在或都不存在:

    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="optionalTag1" minOccurs="0"/>
            <xsd:element name="complulsoryTag1"/>
            <xsd:element name="complulsoryTag2"/>
            <xsd:element name="optionalTag2" minOccurs="0"/>
        </xsd:sequence>
        <!-- Both optional tags are present or none of them are present -->
        <xsd:assert test="boolean(optionalTag1) = boolean(optionalTag2)"/>
    </xsd:complexType>
    

    请注意,这是提出的唯一一个也适用于xs:all 的解决方案。

    【讨论】:

    • 它们不应该在同一个序列中......看我的编辑
    • 我已经用两种可能对您的问题有用的解决方案更新了我的答案。
    • @texasbruce 这些解决方案是否对您有效?
    • @texasbruce 我还在等待答案 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 2015-08-02
    • 2018-01-05
    • 2018-06-01
    • 2022-10-18
    • 1970-01-01
    相关资源
    最近更新 更多