如何在不允许多个根的情况下使用ref属性

时间:2014-02-13 08:39:11

标签: xml xsd ref

我正在尝试使用XSD验证简单的XML,但是我遇到了有关ref属性的问题。

我使用此XSD验证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>

有了这个,我可以有一个文章,其中包含Text或以Text结尾的递归组,但我的问题是它还验证了root是一个Group还是Text节点,我不知道如何引用一个元素不直接位于xs:schema根节点下。

如何仅以root身份验证XML?

谢谢!

1 个答案:

答案 0 :(得分:2)

删除元素的全局声明,并对本地声明的元素使用全局声明的类型:

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

这样,全局声明的唯一元素就是article。