ZVON > Tutorials > XML Schema and Relax NG Tutorial
Index | >> Example 2 / 2 << | Prev | Next |
Contents > Annotation > Extending schema

Extending schema

  1. XML Schema and Schematron combined - xsd:appinfo element
  2. Relax NG
XML Schema keys: appinfo

1. XML Schema and Schematron combined - xsd:appinfo element

If you want to combine XML Schema and Schematron (or other) schema language, you can put the Schematron schema into the element "appinfo", which is a child of "annotation" element. Inspired by "Combining the power of W3C XML Schema and Schematron" article.

Valid document


<root xsi:noNamespaceSchemaLocation="correct_0.xsd" aa="1" bb="2" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <a>3</a>
</root>

Correct XML Schema (correct_0.xsd)
We have a strange requirement - that the element root can have any attributes or elements, but their total count must be 3. The Schematron pattern below - enclosed in "appinfo" element - checks this.


<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >

  <xsd:annotation>
    <xsd:appinfo>
      <pattern name="Total count of attributes and child elements" xmlns="http://www.ascc.net/xml/schematron" >
        <rule context="root">
          <assert test="count(@* | *) = 3"> The total count of attributes and elements is not 3! </assert>
        </rule>
      </pattern>
    </xsd:appinfo>
  </xsd:annotation>

  <xsd:element name="root">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:any namespace="##any" processContents="skip" minOccurs="0" maxOccurs="unbounded"/>
      </xsd:sequence>
      <xsd:anyAttribute namespace="##any" processContents="skip"/>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

2. Relax NG

Relax NG allows you to place arbitrary elements from other namespaces into your schema. I am not sure, if there are any official guidelines, where to properly place the Schematron rules and now it is perhaps implementation dependent. We will place it into "element" element (e.g. SUN MSV accepts this).

Valid document


<root aa="1" bb="2" xmlns="">
  <c>3</c>
</root>

Correct Relax NG schema (correctRelax_0.rng)


<grammar xmlns="http://relaxng.org/ns/structure/1.0" >

  <start>
    <element>
      <pattern name="Total count of attributes and child elements" xmlns="http://www.ascc.net/xml/schematron" >
        <rule context="root">
          <assert test="count(@* | *) = 3"> The total count of attributes and elements is not 3! </assert>
        </rule>
      </pattern>
      <name ns="">root</name>
      <zeroOrMore>
        <attribute>
          <anyName/>
          <text/>
        </attribute>
      </zeroOrMore>
      <zeroOrMore>
        <element>
          <anyName/>
          <text/>
        </element>
      </zeroOrMore>
      <text/>
    </element>
  </start>
</grammar>