【问题标题】:XML schema - how to bind existence of one attribute to existence of another attributeXML 模式 - 如何将一个属性的存在绑定到另一个属性的存在
【发布时间】:2015-02-11 06:38:16
【问题描述】:

我有以下 xml 行:

<customer id="3" phone="123456" city="" />  <!--OK-->
<customer id="4" />                         <!--OK--> 
<customer id="3" phone="123456" />          <!--ERROR-->
<customer id="3" city="" />                 <!--ERROR-->

“电话”和“城市”属性是可选的,但如果“电话”存在,“城市”也应该存在,反之亦然。是否可以在 XML 模式中插入这样的限制?

谢谢。

【问题讨论】:

    标签: xml schema bind


    【解决方案1】:

    XML 中的依赖概念(您称之为“绑定”)是通过嵌套来管理的。因此,如果您希望两个字段相互依赖,您应该将它们定义为嵌套的可选元素的强制属性。

    因此,如果您可以完全控制架构的结构,则可以执行以下操作:

    <customer id="1">
      <contact city="Gotham" phone="batman's red phone" />
    </customer>
    

    其中contact 元素在customer 中是可选的,但cityphonecontact 中是必需的。

    该结构对应的 XSD 如下所示:

      <xs:element name="customer">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="contact" minOccurs="0">
              <xs:complexType>
                <xs:attribute name="city" type="xs:string" use="required"/>
                <xs:attribute name="phone" type="xs:string" use="required"/>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
          <xs:attribute name="id" type="xs:string"/>
        </xs:complexType>
      </xs:element>
    

    【讨论】:

    • 也许 use="required" 是“id”属性所必需的——而 xs:long 应该是对其类型的一个很好的猜测。
    • 如果您无法完全控制架构的结构怎么办?是否可以使用原始帖子的结构来做到这一点?
    猜你喜欢
    • 2010-11-14
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多