问题描述:

Let's say I have an XML file like this:

<?xml version="1.0" encoding="utf-8" ?>

<Books>

<Book

Title="Animal Farm"

Author="George Orwell"

/>

</Books>

Is it possible to author a XSD for this XML file that says: If a Book element has the Title attribute, then the Author attribute must exist too? Note that I'm not asking about restrictions based on the attribute values, just the attribute names.

网友答案:

In XSD 1.0, you'll have to impose that constraint at the application level.

In XSD 1.1, you can use xs:assert to impose the constraint:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Books">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Book" minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="Title"/>
            <xs:attribute name="Author"/>
            <xs:assert test="not(@Title) or @Author"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
相关阅读:
Top