0

我不知道如何命名我的问题。

我有一个包含以下元素的 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 中指定它?

4

1 回答 1

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>
于 2012-05-09T17:14:41.357 回答