Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify an element to have an attribute that states how many children it contains in an XML Schema?

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>
like image 983
sebastien Avatar asked Jun 19 '11 17:06

sebastien


People also ask

What attribute is used to indicate that an attribute is required for an element in the XSD?

Attributes are by default optional. But to make an attribute mandatory, "use" attribute can be used.

How an element can be defined within an XSD?

Each element definition within the XSD must have a 'name' property, which is the tag name that will appear in the XML document. The 'type' property provides the description of what type of data can be contained within the element when it appears in the XML document.

Which allows you to specify which child elements an element can contain?

A complex type is a container for other element definitions, this allows you to specify which child elements an element can contain. This allows you to provide some structure within your XML documents.


2 Answers

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.

like image 63
Michael Kay Avatar answered Nov 11 '22 00:11

Michael Kay


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>
like image 35
Mads Hansen Avatar answered Nov 10 '22 23:11

Mads Hansen