views:

48

answers:

1

Hellow all,

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="" />                 <!--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.

+2  A: 

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>
Welbog
maybe use="required" is needed for "id" attribute - and xs:long should be a good guess for its type.
Brian Clozel