Question

I have an XML which has a part looks like this:
TextData>
TextGroup ID="Group1">
TextGroup ID="Group2">
TextGroup ID=GroupN">
Text ID=SomeID>Some Text

So, inside TextData, there can be 1..N levels of elements, and the lowest level TextGroup MUST contain at least one element.
How can I describe this in XSD? Is it possible at all? So far I have this, but, of course, it only allows me use 2 levels, and also enforces the use of the 2 levels, so not suitable for me:

<xs:element name="TextData">
      <xs:complexType>
        <xs:all>
          <xs:element name="TextGroup">
            <xs:complexType>
              <xs:all>
                <xs:element name="TextGroup">
                  <xs:complexType>
                    <xs:all>
                      <xs:element   name="Text"type="xs:string">                             
                      </xs:element>
Was it helpful?

Solution

At some point, you need to use a reference to one of the elements you have already defined with a name, for example by using a named complex type.

Within each element, instead of using <xs:all>, use <xs:choice>. By doing so, you can make sure that either another level or the string element is the child element at any level.

This could look similar to the following (untested, as I don't see your complete XSD in the question, but you get the idea):

<xs:element name="TextData" type="myTextDataType"/>

<xs:complexType name="myTextDataType">
    <xs:choice>
        <xs:element name="TextGroup" type="myTextDataType"/>
        <xs:element name="Text" type="xs:string"/>
    </xs:choice>
</xs:complexType>

Or, explained in different words:

It's the same "trick" as when building a chain of something in formal grammars. Within the chain, you can choose between a rule that prolongs the chain by adding another non-terminal, "looping back to the current state from where the chain can be further prolonged" (say, A -> aA), and a rule that ends the chain with something irregular (for example, A -> b).

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