为什么我不能使用ref作为XSD中的全局元素的xs:元素?

时间:2013-05-08 14:23:26

标签: xml xsd

我正在< xsd:element >中尝试 ref 属性并且没有得到以下内容:

而< xsd:element >使用 ref 属性可以在非全局范围内定义(即不直接在< 架构>下面),如:

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>

这样,例如以下使用xmllint进行验证:

ref1.xml

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

但是,我不能将引用元素直接放在全局级别。例如。以下内容:

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>

验证下面的 ref2.xml

ref2.xml

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

实际上 xmlint 在解析 xsd 文件时抱怨,甚至在到达 xml 文件之前:

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

更新

根据接受的答案,我发现XML Schema Primer中列出了约束:

  

有一点需要注意,全局声明不能包含引用;全局声明必须直接识别简单和复杂类型。

1 个答案:

答案 0 :(得分:1)

您希望顶级ref提供顶级声明尚未提供的内容?如果

<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>

被允许,它只会说“符合此架构的文档可以在a命名空间中具有名为http://www.dummy-example.com的顶级元素,或者也可以是名为a的顶级元素在http://www.dummy-example.com命名空间中 - 它只会添加

之外的任何内容
<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>