XML模式 - 如何将一个属性的存在绑定到另一个属性的存在

时间:2010-04-14 11:39:31

标签: xml schema bind

我有以下xml行:

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

“phone”和“city”属性是可选的,但如果“phone”存在,则“city”也应该存在,反之亦然。是否可以将这种限制插入XML模式?

感谢。

1 个答案:

答案 0 :(得分:2)

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

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

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

contact元素在customer中是可选的,但city中必须phonecontact

该结构的相应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>