2个元素中的元素引用

时间:2012-05-09 16:53:34

标签: xsd

我不知道如何标题我的问题。

我有一个包含以下元素的XSD

 <xs:element name="abc">
   <xs:complexType>
     <xs:element maxOccurs="unbounded" ref="ele1"/>
   </xs:complexType>
 </xs:element>

 <xs:element name="xyz">
   <xs:complexType>
     <xs:element maxOccurs="unbounded" ref="ele1"/>
   </xs:complexType>
 </xs:element>

 <xs:element name="ele1">
   <xs:complexType>
     <xs:attribute name="ID" type="xs:integer"/>
   </xs:complexType>
 </xs:element>

问题是元素xyz ID是强制性的,而abc则不是;如何在XSD中指定它?

1 个答案:

答案 0 :(得分:0)

假设ID是在“容器”下重复的内容的唯一标识符,那么您可以为xyz设置xs:key约束,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="abc">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="unbounded" ref="ele1"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element name="xyz">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="unbounded" ref="ele1"/>
            </xs:sequence>
        </xs:complexType>
        <xs:key name="PK_xyz">
            <xs:selector xpath="ele1"/>
            <xs:field xpath="@ID"/>
        </xs:key>
    </xs:element>
    <xs:element name="ele1">
        <xs:complexType>
            <xs:attribute name="ID" type="xs:integer"/>
        </xs:complexType>
    </xs:element>
</xs:schema>

然后,因为ID丢失而导致XML无效:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<xyz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ele1 ID="1"/>
    <ele1 />
</xyz>

错误讯息:

Error occurred while loading [], line 5 position 3
The identity constraint 'PK_xyz' validation has failed. Either a key is missing or the existing key has an empty node.
Document3.xml is invalid.

无效,因为它是重复的(如果上述关于唯一性的假设不成立,则这是缺点):

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<xyz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ele1 ID="1"/>
    <ele1 ID="1"/>
</xyz>

错误:

Error occurred while loading [], line 5 position 3
There is a duplicate key sequence '1' for the 'PK_xyz' key or unique identity constraint.
Document3.xml is invalid.

工作样本:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<xyz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ele1 ID="1"/>
    <ele1 ID="2"/>
</xyz>