XML schema - how to relate the existence of one attribute to the 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="" /> <!--ERROR--> 

β€œphone” and β€œcity” attributes are optional, but if there is a β€œphone”, there is also a β€œcity” and vice versa. Is it possible to insert such a restriction into an XML schema?

Thanks.

+4
source share
1 answer

The concept of dependencies (which you call "binding") in XML is controlled through nesting. Therefore, if you want the two fields to depend on each other, you must define them as mandatory attributes of a nested, optional element.

So, if you have full control over the structure of the circuit, you can do something like this:

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

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

The corresponding XSD for this 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> 
+2
source

Source: https://habr.com/ru/post/1306906/


All Articles