Yossi Dahan [BizTalk]

Google
 

Thursday, September 22, 2005

Creating a schema that allows child elements to apear in any order

For a long time I was under the impression that in an xml document the order in which child elements appear under their parent element is not important.

I guess it comes down the fact that xml always seems to simply "make sense" and be flexible and readable that you wouldn't expect (well - I didn't!) that such thing as the order of elements would be inforced.
After all the impression is that while there's clearly a parent-child relationship in xml, there's no sibling relationship. not directly anyway.

The bottom line is that it does. when you simply create a sequence element the order in which the child elements appear in the schema is the order they must appear in the xml instance.

So...with the following xsd:
<xs:element name="Person">
<xs:complexType>
<xs:sequence>
<xs:element name="FirstName" type="xs:string" />
<xs:element name="LastName" type="x:string" />
</xs:sequence>
</xs:complexType>
</xs:element>

The following xml instance is valid:

<Person>
<FirstName>Yossi</FirstName>
<LastName>Dahan></LastName>
</Person>

but this one is not:

<Person>
<LastName>Dahan></LastName>
<FirstName>Yossi</FirstName>
</Person>

Now clearly both xml instances describe the same entity, and in this case, the order in which the child elements appear is irrelevant.

So - how do you create a schema in which the order is not enforced? quite simply it appears - by using a choice element.

<xs:element name="Person" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:choice maxOccurs="unbounded">
<xs:element name="FirstName" minOccurs="0"/>
<xs:element name="LastName" minOccurs="0"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>

Tthe important thing to notice is the maxoccurs on the choice element - this allows the actual repetition of each child element in the sequnce, but becuase they are in a sequence and both child elements have minoccurs=0 they can appear in any order.

It's been a while since I found the answer to this one, and at the time I thought I must be the only one being confused about this one, but recently I've seen/asked this question more then once so I've decided to mention this here.

1 Comments:

  • thanks yossi your not the only one confused about this one but as usual im nearly 10 years behind you :-)

    Mike

    By Blogger Unknown, at 17/07/2014, 14:19  

Post a Comment

<< Home