Question

I'm trying to validate a simple XML using XSD, however i'm facing a problem concerning the ref attribute.

I use this XSD to validate the XML :

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="unqualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="article">
        <xs:complexType>
            <xs:choice maxOccurs="unbounded" minOccurs="1">
                <xs:element ref="text" maxOccurs="unbounded" minOccurs="0" />
                <xs:element ref="group" maxOccurs="unbounded" minOccurs="0" />
            </xs:choice>
        </xs:complexType>   
    </xs:element>

    <xs:element name="group">
        <xs:complexType>
            <xs:choice maxOccurs="unbounded" minOccurs="1">
                <xs:element ref="group" maxOccurs="unbounded" minOccurs="0" />
                <xs:element ref="text" maxOccurs="unbounded" minOccurs="0" />
            </xs:choice>
            <xs:attribute type="xs:string" name="name" use="optional" />
        </xs:complexType>
    </xs:element>

    <xs:element name="text" type="xs:string" />

</xs:schema>

With this, i can have an Article which contains Text or recursive Groups ending by Text but my problem is that it also validate if the root is a Group or a Text node and i don't know how to ref an element which isn't directly under the xs:schema root node.

What can i do to validate only the XML with Article as root ?

Thanks!

Was it helpful?

Solution

Remove the global declarations for the elements, and use globally declared types for locally declared elements:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="unqualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="article">
        <xs:complexType>
            <xs:choice maxOccurs="unbounded" minOccurs="1">
                <xs:element name="text" type="xs:string" maxOccurs="unbounded" minOccurs="0" />
                <xs:element name="group" type="groupType" maxOccurs="unbounded" minOccurs="0" />
            </xs:choice>
        </xs:complexType>   
    </xs:element>

    <xs:complexType name="groupType">
        <xs:choice maxOccurs="unbounded" minOccurs="1">
            <xs:element name="group" type="groupType" maxOccurs="unbounded" minOccurs="0" />
            <xs:element name="text" type="xs:string" maxOccurs="unbounded" minOccurs="0" />
        </xs:choice>
        <xs:attribute type="xs:string" name="name" use="optional" />
    </xs:complexType>
</xs:schema>

This way the only element declared globally is article.

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