【问题标题】:XSD - one of 2 attributes is required?XSD - 需要 2 个属性之一?
【发布时间】:2010-10-20 06:27:55
【问题描述】:

有没有办法指定 XSD 中需要 2 个属性之一?

例如,我有一个这样的定义:

<xs:attribute name="Name" type="xs:string" use="optional" />
<xs:attribute name="Id" type="xs:string" use="optional" />

我希望能够定义至少其中一项是必需的。这可能吗?

【问题讨论】:

    标签: xsd


    【解决方案1】:

    不,我不认为你可以用属性来做到这一点。您可以将两个 &lt;xs:element&gt; 包装成一个 &lt;xs:choice&gt; - 但对于属性,恐怕没有等效的构造。

    【讨论】:

    • 这不适用于具有相同名称的多个元素...即我想要某个名称的元素的三种可能组合,并选择具有相同名称的三种复杂类型失败:(
    【解决方案2】:

    XSD 1.1 将允许您使用断言来执行此操作。

    <xsd:element name="remove">
        <xsd:complexType>                        
            <xsd:attribute name="ref" use="optional"/>
            <xsd:attribute name="uri" use="optional"/>
            <xsd:assert test="(@ref and not(@uri)) or (not(@ref) and @uri)"/>            
        </xsd:complexType>
    </xsd:element>
    

    【讨论】:

    • 不错的解决方案,但由于它于 2012 年发布 (w3.org/TR/xmlschema11-1) 并且我使用的是 .NET 4.0(2010 年发布),因此不受支持。 .NET 4.5 是否支持它?示例类:msdn.microsoft.com/en-us/library/swxzdhc0(v=vs.110).aspx
    • 我们不能做类似&lt;xsd:assert test="(@ref or @uri)"/&gt; 的事情吗?
    • 我不相信 xsl 'or' 是排他性的。我们希望它是其中之一,但不是两者兼而有之。
    【解决方案3】:

    Marc 说的很对……你不能在 XSD 中的 xs:choice 父元素中包含 xs:attribute 子元素。

    逻辑似乎是,如果一个元素的两个实例具有一组互斥的属性,那么它们在逻辑上是两个不同的元素。

    Jeni Tennison here 提出了解决此问题的方法。

    【讨论】:

      【解决方案4】:

      您应该查看 W3C wiki 上的以下页面:Simple attribute implicationAttribute muttex

      【讨论】:

        【解决方案5】:

        该示例定义了一个名为“person”的元素,该元素必须包含“employee”元素或“member”元素。

        <xs:element name="person">
          <xs:complexType>
            <xs:choice>
              <xs:element name="employee" type="employee"/>
              <xs:element name="member" type="member"/>
            </xs:choice>
          </xs:complexType>
        </xs:element>
        

        【讨论】:

        • 问题不在于元素,而在于属性。
        猜你喜欢
        • 2012-03-01
        • 1970-01-01
        • 2015-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多