Pages

Tuesday, October 25, 2011

Use xsd:extension to add functionality to XSD elements

You can create name complexTypes to reuse common content models, but let’s take it a step further with extended types. Here’s your predefined complexType and the elements that reference it:

<xsd:complexType name="runtextType" mixed="true">
   <xsd:choice minOccurs="0" maxOccurs="unbounded">
      <xsd:element ref="emph"/>
      <xsd:element ref="sub"/>
      <xsd:element ref="sup"/>
      <xsd:element ref="footref"/>
      <xsd:element ref="xref"/>
      <xsd:element ref="graphic"/>
   </xsd:choice>
</xsd:complexType>


<xsd:element name="para" type="runtextType"/> 
<xsd:element name="title" type="runtextType"/>
<xsd:element name="articleTitle" type="runtextType"/>

But you want the article-title to have an ID attribute as well. In DTDs, you can simply add the ID attribute to the element. In XSD, attributes must be part of a complexType. However, you can’t include a complexType in an element that already has a defined type. You could simply add an attribute to runtextType, but then that attribute would be applicable to para and title as well, which we don’t want. The other option is to use an "extended" type definition.

Create a new complexType named articleTitleType. Use xsd:complexContent and xsd:extension to reference the runtextType definition. Then, add an ID attribute to the new, extended type definition:

<xsd:complexType name="articleTitleType" mixed="true">
   <xsd:complexContent>
      <xsd:extension base="runtextType">
         <xsd:attribute name="id" type="xsd:ID"/>
      </xsd:extension>
   </xsd:complexContent>
</xsd:complexType>

Now, change the type of articleTitle to reference this new type:

<xsd:element name="articleTitle" type="articleTitleType"/>

This way, articleTitle still shares the runtextType content model, but now it has an ID attribute as well.


No comments:

Post a Comment

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