bez
bez

Reputation: 187

recursive xml schema generation

I have an xml with a recursive element such as in the example below. A contains a sequence of B elements. Each B element contain a C, D, E and F element. Each F except the last one in the sequence contains a B element.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<A>
  <B>
    <C></C>
    <D></D>
    <E></E>
          <F>
            <B> 
              <C></C>
              <D></D>
              <E></E>
                    <F>  
                      <B> 
                        <C></C>
                        <D></D>
                        <E></E>
                        <F></F>
                      </B>
                    </F>
           </B>
        </F>
   </B>
</A>

When I generate a schema for this xml using an online generator I get a really long schema file. Is there no way to write a shorter recursive schema for this xml?

enter image description here

Upvotes: 1

Views: 581

Answers (2)

Iurii  Kvashuk
Iurii Kvashuk

Reputation: 409

In your case where each element F except the last one in the sequence contains B element, I can offer tge following schema. By using choice constuction it is possible to make last F element not recursive. This schema validates correctly, but I'm not sure can it be an graceful solution.

<xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" xmlns="http://tempuri.org/XMLSchema.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="A">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="B" type="B" minOccurs="0"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="F" type="B"/>
  <xsd:complexType name="B">
    <xsd:sequence>
      <xsd:element name="C" type="xsd:string" minOccurs="0" maxOccurs="1"/>
      <xsd:element name="D" type="xsd:string" minOccurs="0" maxOccurs="1"/>
      <xsd:element name="E" type="xsd:string" minOccurs="0" maxOccurs="1"/>
      <xsd:choice>
        <xsd:element ref="F" minOccurs="0" maxOccurs="1"/>
        <xsd:element name="F" type="xsd:string" minOccurs="0" maxOccurs="1"/>
      </xsd:choice>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema> 

Upvotes: 2

Michael Kay
Michael Kay

Reputation: 163322

Of course a recursive schema can be written. For any instance document, there's any number of schemas that can be used to describe it accurately, but the difficult thing for an automatic schema generator is to spot the patterns that describe it elegantly: that is, to guess what other instance documents you might want the schema to accept as well.

The typical way to write a recursive schema is to use named global types (though it can also be done with named global element declarations). Something like:

<xs:element name="A" type="A-type"/>

<xs:complexType name="A-type">
  <xs:sequence>
    <xs:element ref="A" minOccurs="0"/>
  </xs:sequence>
</xs:complexType>

Upvotes: 0

Related Questions