Pages

Wednesday, February 6, 2013

Streamline your XML Schema with substitution groups

Creating reusable content models is an important part of Schema design. Substitution groups provide one method to streamline your Schema and add flexibility to your model. They consist of a head element and one or more member elements. Any place the head element is referenced in your Schema, the member elements can be substituted for it. In fact, the head may be set simply as a placeholder as we'll see below.

Let's define an element named "para-sec":

<xsd:element name="para-sec" abstract="true"/>

Setting the abstract attribute to "true" means that the element para-sec will never appear as a tag in your data. Only the elements that are included in the para-sec substitution group will be available.

Next, define the elements you want to include in the substitution group. We'll set up para to handle standard paragraph content, table-para to include tabular data, and section to handle titled sections (which contain paragraphs). Use the substitutionGroup attribute to enable you to substitute these elements for para-sec wherever it's referenced in the Schema.

<xsd:element name="para" substitutionGroup="para-sec" type="paracontent"/>

<xsd:element name="table-para" substitutionGroup="para-sec">
    <xsd:complexType>
      <xsd:sequence>
       <xsd:element ref="table"/>
       <xsd:element ref="tablenote" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
</xsl:element>

<xsd:element name="section" substitutionGroup="para-sec">
    <xsd:complexType>
      <xsd:sequence>
       <xsd:element ref="title"/>
       <xsd:element ref="para-sec" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
</xsd:element>


Now you can reference the substitution group as the content model in other elements:

<xsd:element name="topic">
    <xsd:complexType>
      <xsd:sequence>
       <xsd:element ref="title"/>
       <xsd:element ref="para-sec" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
</xsd:element>


The topic element can now contain an initial title followed by one or more of any members of the para-sec substitution group, in any order. Adding new members to the group automatically makes them available to "topic" in this instance.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.