tags:

views:

3880

answers:

2

I need to create an XSD schema that validates a tree structure of an XML document. I don't know exactly the ocurrences or depth level of the tree.

XML example:

<?xml version="1.0" encoding="utf-8"?>
<node>
  <attribute/>
    <node>
      <attribute/>
      <node>
      </node>      
  </node>
</node>

Which is the best way to validate it?

Thanks

+4  A: 

XSD does indeed allow for recursion of elements. Here is a sample for you

<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>

As you can see the section element contains a child element that is of type section.

Mike Brown
+1 I believe this is a better solution than the accepted one as it permits the recursive element to be a ComplexType.
Noel Abrahams
Thanks for the compliment!
Mike Brown
+12  A: 

if you need a recursive type declaration, here is an example that might help:

<xs:schema id="XMLSchema1"
    targetNamespace="http://tempuri.org/XMLSchema1.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema1.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema1.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:element name="node" type="nodeType"></xs:element>

  <xs:complexType name="nodeType">    
    <xs:sequence minOccurs="0" maxOccurs="unbounded">
      <xs:element name="node" type="nodeType"></xs:element>
    </xs:sequence>
  </xs:complexType>

</xs:schema>

As you can see, this defines a recursive schema with only one node named "node" which can be as deep as desired.

Dani Duran