7

Is it even possible?

  • I know it’s possible to do a restriction based on regex, but that’s not it
  • I know it’s possible to declare an attribute as a foreign key calculated by an XPath, but it seems it has to be unique

Exemple:

<root children="2">
    <child />
    <child />
</root>
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
sebastien
  • 418
  • 4
  • 7

2 Answers2

6

XSD 1.1 allows you to express this kind of constraint:

<xs:element name="root">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="child" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="children" type="xs:integer"/>
  </xs:complexType>
  <xs:assert test="@children = count(child)"/>
</xs:element>

XSD 1.1 is currently implemented in Saxon and Xerces.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
5

W3C Schema 1.0 doesn't have the ability to constrain the attribute values based upon the instance document.

Schematron is a great tool for validating that documents adhere to such custom validation scenarios.

For example:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://purl.oclc.org/dsdl/schematron">
    <pattern>
        <rule context="root[@children]">
            <assert 
                id="children-value" 
                test="@children=count(child)" 
                flag="error">
                The root/@children value must be equal to the number of child elements.
                </assert>
            </rule>
    </pattern>
</schema>
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147