ZVON > Tutorials > XML Schema and Relax NG Tutorial
Index | >> Example 8 / 10 << | Prev | Next |
Contents > Simple types > Element can have [x,y] either as attributes or as elements

Element can have [x,y] either as attributes or as elements

  1. XML Schema
  2. Relax NG
XML Schema keys:
Relax NG keys: choice, attribute, element

1. XML Schema

Now, we want the "root" element to have either "x" and "y" attributes, or "x" and "y" elements (but not both at the same time). I do not know, how to do this with XML Schema.

2. Relax NG

You can easily choose between a group of attributes and a group of elements.

Valid document


<root x="1" y="2" xmlns=""/>

Valid document
The order of attributes is not important, so this document is valid too.


<root y="10" x="5" xmlns=""/>

Valid document


<root xmlns="">
  <x/>
  <y/>
</root>

Invalid document
The ordering of elements is wrong ("x" must come first according to schema).


<root xmlns="">
  <y/>
  <x/>
</root>

Invalid document


<root x="1" xmlns="">
  <y>3</y>
</root>

Correct Relax NG schema (correctRelax_0.rng)


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

  <start>
    <element>
      <name ns="">root</name>
      <choice>
        <group>
          <element name="x">
            <text/>
          </element>
          <element name="y">
            <text/>
          </element>
        </group>
        <group>
          <attribute name="x">
            <text/>
          </attribute>
          <attribute name="y">
            <text/>
          </attribute>
        </group>
      </choice>
    </element>
  </start>
</grammar>