Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27286

why can't I have an xs:element using ref as a global element in a XSD?

I am experimenting with ref attributes in <xsd:element> and don't get the following:

while an <xsd:element> with a ref attribute can be defined in the non-global scope (i.e. not directly below <schema>), as in:

ref1.xsd

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.dummy-example.com"
xmlns:foo="http://www.dummy-example.com">


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

<xs:element name="b">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="foo:a"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>

So that, e.g. the following validates with xmllint:

ref1.xml

<?xml version="1.0"?>
<foo:b xmlns:foo="http://www.dummy-example.com">
    <foo:a>whatever ...</foo:a>
</foo:b>

However, I cannot have the referencing element be directly at the global level. E.g. the following:

ref2.xsd

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.dummy-example.com"
xmlns:foo="http://www.dummy-example.com">
    <xs:element name="a" type ="xs:string"/>
    <xs:element ref="foo:a"/>
</xs:schema>

does not validate ref2.xml below:

ref2.xml

<?xml version="1.0"?>
<foo:a xmlns:foo="http://www.dummy-example.com">
    whatever
 </foo:a>   

In fact xmlint complains during the parsing of the xsd file, even before reaching the xml file:

ref2.xsd:6: element element: Schemas parser error : Element '{http://www.w3.org/2001/XMLSchema}element': The attribute 'name' is required but missing.

UPDATE

Following the accepted answer, I found the constraint spelled out in the XML Schema Primer:

One caveat is that global declarations cannot contain references; global declarations must identify simple and complex types directly.

Upvotes: 1

Views: 967

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

What would you expect a top level ref to provide that a top level declaration doesn't already give you? If

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.dummy-example.com"
xmlns:foo="http://www.dummy-example.com">
    <xs:element name="a" type ="xs:string"/>
    <xs:element ref="foo:a"/>
</xs:schema>

were allowed, it would just say "a document conforming to this schema can have a top level element named a in the http://www.dummy-example.com namespace, or alternatively a top level element named a in the http://www.dummy-example.com namespace" - it would add nothing beyond simply

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.dummy-example.com"
xmlns:foo="http://www.dummy-example.com">
    <xs:element name="a" type ="xs:string"/>
</xs:schema>

Upvotes: 1

Related Questions