2
votes

i want to create a xml schema that allows only one single root node .

In the structure below the root node, there is an element that i want to reuse in different locations.

My first approach was to create a global element in the schema, but if i do so, a xml document having only a tag as root is also valid against this schema.

How do i create global elements that are only allowed to be used as ref-element inside my root-structure?

This is what i want to have:

<root>
  <branch>
     <leaf/>
  </branch>
  <branch>
     <fork>
        <branch>
          <leaf/>
        </branch>
        </leaf>
     </fork>
</root>

But this would also be valid <leaf/> as root node

1

1 Answers

0
votes

XML has always only one root node. It represents a hierarchic structure and is bound to its schema. So you can't change the root element with the same schema and being valid.

At first it should be well-formed like this:

<?xml version="1.0" encoding="UTF-8"?>

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-scheme.xsd>
    <branch>
        <leaf/>
    </branch>
    <branch>
        <fork>
            <branch>
                <leaf/>
            </branch>
            <leaf/>
        </fork>
    </branch>
</root>

I would suggest a scheme like this:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:complexType name="root">
        <xs:sequence>
            <xs:element ref="branch" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="branch">
        <xs:choice>
            <xs:element ref="fork" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element ref="leaf" minOccurs="0" maxOccurs="unbounded"/>
        </xs:choice>
    </xs:complexType>
    <xs:complexType name="fork">
        <xs:sequence>
            <xs:element ref="branch" minOccurs="0" maxOccurs="unbounded"/>
            <xs:element ref="leaf" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="leaf"/>
    <xs:element name="root" type="root"/>
    <xs:element name="branch" type="branch"/>
    <xs:element name="fork" type="fork"/>
    <xs:element name="leaf" type="leaf"/>
</xs:schema>

I hope it helps you.