Pages

Thursday, January 2, 2014

How to manage recursive elements with XSD

A question that arises often as developers move into XML and Schemas is: Can you define recursive structures in XSD? The answer is: Yes you can.

A common example would be recursive <section> elements:

<xsd:element name="section">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="title"/>
<xsd:element ref="para" maxOccurs="unbounded"/>
<xsd:element ref="section" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>


This rule states that a section can contain a title, one or more paras, and zero or more sections. Note that there is no minOccurs on para, but there is a maxOccurs. If there is no minOccurs, then the default is one. We set a maxOccurs to allow multiple paras.

Note also that this content applies to all sections, including nested sections. Therefore, there's no limit to how deeply you can nest section elements and maintain the content model.



No comments:

Post a Comment

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