假設ID是在「容器」重複內容的唯一標識符,那麼你可以設置一個XS:鍵約束的XYZ是這樣的:
<?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>
然後,無效的XML因爲ID是失蹤:
<?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>