Linkwerk Logo

An example of Context-sensitive Content Models in Relax NG

At several places you can read, that Relax NG supports context-sensitive content models. I needed a small example of that feature, that fits on a presentation slide. Since I couldn't find one within 5 minutes, I wrote my own. Maybe you can use it.

A Relax-NG-Schema

The following Schema defines an element type d with a content model, that depends on the ancestor context in which the element d is actually placed. Please note that the content model of c is always d.

<grammar xmlns="http://relaxng.org/ns/structure/1.0">
<!-- This is a small demonstration of Relax NG's context sensitive content model feature. Details at http://www.linkwerk.com/pub/relaxng/context-sensitive-content-models/ -->
<start>
<element name="root">
<choice>
<element name="a">
<element name="c">
<ref name="d-descendant-of-a"></ref>
</element>
</element>
<element name="b">
<element name="c">
<ref name="d-descendant-of-b"></ref>
</element>
</element>
</choice>
</element>
</start>
<define name="d-descendant-of-a">
<element name="d">
<element name="e">
<text></text>
</element>
</element>
</define>
<define name="d-descendant-of-b">
<element name="d">
<element name="f">
<text></text>
</element>
</element>
</define>
</grammar>

Two valid instances

The following two XML instances both validate against the above schema.

test1.xml:

<root>
<a>
<c>
<d>
<e></e>
</d>
</c>
</a>
</root>

test2.xml:

<root>
<b>
<c>
<d>
<f></f>
</d>
</c>
</b>
</root>

Recommended Articles


Stefan Mintert, $Date: 2005/06/10 14:09:57 $ (UTC)