开发者

XML schema - how to bind existence of one attribute to existence of another attribute

I have the following xml lines:

<customer id="3" phone="123456" city="" />  <!--OK-->
<customer id="4" />                         <!--OK--> 
<customer id="3" phone="123456" />          <!--ERROR-->
<customer id="3" city="" />                 &l开发者_开发知识库t;!--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?

Thanks.


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.

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:

  <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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜