Reputation: 610
The W3Schools site describes an improvement to a basic XML Schema layout by defining the types at the start of a schema definition and referencing these types later within other complexTypes. Here is an example:
<xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- definition of simple elements -->
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
<!-- definition of complex elements -->
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element ref="name"/>
<xs:element ref="address"/>
<xs:element ref="city"/>
<xs:element ref="country"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
It is my understanding that this simplifies the structure of the schema by having a common place to define simple elements and attributes.
My question is - does this not allow for the defined elements to be placed within a valid XML file as top-level elements? For example, would the following snippet be valid with regards to the schema:
<name>Foo</name>
<name>Bar</name>
<shipto>
<name>...</name>
<address>...</address>
...
</shipto>
This seems like unintended behaviour not really related to the purpose of defining and referencing elements in a schema definition.
Can anyone add any comments on the best practice for handling this situation?
Upvotes: 1
Views: 2135
Reputation: 163645
It's not unintended behaviour, its intended. The philosophy of XSD is that if
<a><b><c/></b></a>
is valid, then in general
<b><c/></b>
is also valid: in a valid document, every fragment is valid.
That may not be what you want, but it's what the XSD designers wanted. The onus is on the recipient to say not "I want the document to be valid", but "I want the document to be valid against the declaration of element a". (Sadly, some APIs for schema processors do not actually allow you to say this.)
Upvotes: 1