ZVON > Tutorials > XML Schema and Relax NG Tutorial
Index | >> Example 8 / 10 << | Prev | Next |
Contents > Wildcard patterns > Exact number of elements from any namespace

Exact number of elements from any namespace

  1. XML Schema
  2. Relax NG
XML Schema keys: maxOccurs

1. XML Schema

The root element named "root" can have 1 to 3 elements from any namespace.

Valid document


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

Valid document


<root xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <x:b xmlns:x="http://foo" />
  <x:c xmlns:x="http://foo" />
  <a/>
</root>

Invalid document
There must at least one element under "root" (here is zero).


<root xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />

Invalid document
There must not be more than three elements under "root" - one element is extra here.


<root xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <a/>
  <x:b xmlns:x="http://foo" />
  <x:c xmlns:x="http://foo" />
  <x:d xmlns:x="http://foo" />
</root>

Correct XML Schema (correct_0.xsd)
We must set the "minOccurs" and "maxOccurs" attributes to 1 and 3, respectively.


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

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

2. Relax NG

The element "anyName" says that the elements can have any name from any namespace. We will use the "optional" element.

Valid document


<root xmlns="">
  <a/>
</root>

Valid document


<root xmlns="">
  <x:b xmlns:x="http://foo" />
  <x:c xmlns:x="http://foo" />
  <a/>
</root>

Invalid document
There must at least one element under "root" (here is zero).


<root xmlns=""/>

Invalid document
There must not be more than three elements under "root" - one element is extra here.


<root xmlns="">
  <a/>
  <x:b xmlns:x="http://foo" />
  <x:c xmlns:x="http://foo" />
  <x:d xmlns:x="http://foo" />
</root>

Correct Relax NG schema (correctRelax_0.rng)


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

  <start>
    <element>
      <name ns="">root</name>
      <ref name="oneAnyElement"/>
      <optional>
        <ref name="oneAnyElement"/>
      </optional>
      <optional>
        <ref name="oneAnyElement"/>
      </optional>
    </element>
  </start>

  <define name="oneAnyElement">
    <element>
      <anyName/>
      <text/>
    </element>
  </define>
</grammar>