Question

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

XML example:

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

Which is the best way to validate it? Recursion?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top