开发者

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

开发者 https://www.devze.com 2023-03-13 20:08 出处:网络
Is it even possible? I know it’s possible to do a restriction based on regex, b开发者_如何学Gout that’s not it

Is it even possible?

  • I know it’s possible to do a restriction based on regex, b开发者_如何学Gout 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>


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.


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消