XML Schema - 是否可以在整个文档中仅允许某个元素一次?

时间:2011-10-05 12:58:06

标签: xml xsd

我想扩展XHTML以将其用作模板语言。我有一个标记标记,如

 <mylang:content/>

我希望此标记标记显示在divp可以显示的位置,但在完整文档中只显示一次。我认为XML Schema是不可能的,但也许一些XML Schema大师知道的更好。

当允许包含元素出现无界时,是否可以在整个文档中仅允许某个元素一次?

2 个答案:

答案 0 :(得分:3)

如果您知道根元素将是,那么我认为您可以在doc元素

上定义约束
<xs:unique name="one-content">
  <xs:selector xpath=".//mylang:content"/>
  <xs:field xpath="."/>
</xs:unique>

这表示所有mylang:content后代必须具有不同的字符串值;但由于元素被约束为空,如果每个元素必须是不同的,那么只能有一个元素。

在XSD 1.1中,当然断言变得容易了。

答案 1 :(得分:0)

完整示例

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="html">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="body" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="body">
        <xs:complexType>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:element ref="content" />
            </xs:choice>
        </xs:complexType>
        <xs:unique name="content">
            <xs:selector xpath="content" />
            <xs:field xpath="." />
        </xs:unique>
    </xs:element>

    <xs:element name="content">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:maxLength value="0" />
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
</xs:schema>

谨防: - 如果在架构中添加targetNamespace,则唯一约束会突然停止工作。这是因为xs:unique,xs:key和xs:keyref不使用默认命名空间。你必须像这样改变你的架构:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema 
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   targetNamespace="http://www.w3.org/1999/xhtml" 
   xmlns="http://www.w3.org/1999/xhtml">

    <xs:element name="html">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="body" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="body">
        <xs:complexType>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:element ref="content" />
            </xs:choice>
        </xs:complexType>
        <xs:unique name="content" xmlns:html="http://www.w3.org/1999/xhtml">
            <xs:selector xpath="content" />
            <xs:field xpath="." />
        </xs:unique>
    </xs:element>

    <xs:element name="content">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:maxLength value="0" />
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
</xs:schema>
相关问题