Pages

Wednesday, June 27, 2012

Define a reusable attributeGroup in your XML Schema

In XML Schema, you can set up an attribute group to share a common attribute set with any number of elements. For example, you might want to include id, creation date, and revision date attributes on all major elements in your data set.

First, set up an attributeGroup like so:

<xsd:attributeGroup name="attlist-idgroup">
    <xsd:attribute name="id" use="required" type="xsd:ID"/>
    <xsd:attribute name="creation-date"/>
    <xsd:attribute name="revision-date"/>
</xsd:attributeGroup>

This group defines "id" as required and of the type "xsd:ID". The creation-date and revision-date attributes have no further definition, which then defaults to implied with a type of "string".

You can then add this attribute group to an element like so:

<xsd:element name="article">
    <xsd:complexType>
      <xsd:complexContent>
       <xsd:extension base="articleContent">
          <xsd:attributeGroup ref="attlist-idgroup"/>
       </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
</xsd:element>

This example assumes a predefined complexType named "articleContent". It then utilizes an <xsd:extension> to call "articleContent" and add the "attlist-idgroup" attributeGroup to it. You can then apply this same method to each element needing to use this attributeGroup.

You can also add the attributeGroup directly to the content model of a given element:

<xsd:element name="appendix">
    <xsd:complexType>
      <xsd:sequence>
       <xsd:element ref="title"/>
       <xsd:element ref="para" maxOccurs="unbounded"/>
      </xsd:sequence>
      <xsd:attributeGroup ref="attlist-idgroup"/>
    </xsd:complexType>
</xsd:element>

In this way, you simply define the sequence followed by the attributeGroup. You can add attributeGroups where individually defined attributes are used.



No comments:

Post a Comment

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