XML Schema: root element

Solution 1:

As far as I know, any globally defined element can be used as root element, and XML Schema does not have a notion for specifying what the root element is supposed to be.

You can however work around this by designing your XML Schema well, so that there is only one globally defined element - then only this element is valid as root element.

An example of this can be found at W3Schools (heading Using Named Types) This example only has one globally defined element, and thus only one possible root element.

Solution 2:

Not everyone agrees with it, but the fact that XML Schema can't specify a root element is by design. The thinking is that if an <invoice> is valid when it's the only thing in a document, then it is equally valid if it is contained in something else. The idea is that content should be reusable, and you shouldn't be allowed to prevent someone using valid content as part of something larger.

(The fact that ID and IDREF are scoped to a document rather goes against this policy; but then the language was designed by a rather large committee.)

Solution 3:

yes, you are right. the xsd should be:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<!-- definition of attributes -->
<xs:attribute name="orderid" type="xs:string"/>

<!-- definition of complex elements -->
<xs:complexType name="shiptoType">
  <xs:sequence>
    <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:sequence>
</xs:complexType>

<xs:complexType name="itemType">
  <xs:sequence>
    <xs:element name="title" type="xs:string" />
    <xs:element name="note" minOccurs="0" type="xs:string" />
    <xs:element name="quantity" type="xs:string" />
    <xs:element name="price" type="xs:string" />
  </xs:sequence>
</xs:complexType>

<xs:element name="shiporder">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="orderperson" type="xs:string" />
      <xs:element name="shipto" type="shiptoType"/>
      <xs:element name="item" maxOccurs="unbounded" type="itemType"/>
    </xs:sequence>
    <xs:attribute ref="orderid" use="required"/>
  </xs:complexType>
</xs:element>

</xs:schema>

as you see, now there is only one xs:element, and that one is the only one that can be a valid root element :)