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

时间:2021-12-06 12:17:17

I have the following xml lines:

我有以下xml行:

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

"phone" and "city" attributes are optional, but if "phone" exists, also "city" should exists and vise versa. Is it possible to insert such restriction to XML schema?

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

Thanks.

1 个解决方案

#1


2  

The concept of dependencies (which you are calling "binding") in XML is managed through nesting. So if you want two fields to be dependent on one another, you should define them as mandatory attributes of a nested, optional element.

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

So if you have full control over the schema's structure, you could do something like this:

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

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

Where the contact element is optional within customer, but city and phone are mandatory within contact.

如果联系人在客户中是可选的,但城市和电话在联系中是强制性的。

The corresponding XSD for that structure would be something like this:

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

#1


2  

The concept of dependencies (which you are calling "binding") in XML is managed through nesting. So if you want two fields to be dependent on one another, you should define them as mandatory attributes of a nested, optional element.

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

So if you have full control over the schema's structure, you could do something like this:

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

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

Where the contact element is optional within customer, but city and phone are mandatory within contact.

如果联系人在客户中是可选的,但城市和电话在联系中是强制性的。

The corresponding XSD for that structure would be something like this:

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