嘿,我想强制一个属性在我的 XML 文档中是唯一的。我刚刚开始使用 XML。我想让每个人都有一个唯一的ID。我看过 xs:unique 但不太清楚它在哪里,每次尝试时都不会解析。架构如下:
<?xml version='1.0' encoding='utf-8'?>
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='people' type='peopleType' /><!-- Root Element -->
<xs:complexType name='peopleType'>
<xs:sequence>
<xs:element name='person' type='personType' maxOccurs='unbounded'/>
</xs:sequence>
</xs:complexType><!-- End peopleType-->
<xs:complexType name='personType'>
<xs:sequence>
<xs:element name='name' type='nameType' maxOccurs='unbounded' />
<xs:element name='email' minOccurs='1'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:pattern value='([a-zA-Z0-9_-])*([.])?([a-zA-Z0-9_-])*([.])?([a-zA-Z0-9_-])*[@]([a-zA-Z0-9_-])*([.])?([a-zA-Z0-9_-])*([.])?([a-zA-Z0-9_-])*' />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name='favColour' type='colourType' minOccurs='0' />
</xs:sequence>
<xs:attribute name='id' type='xs:integer' />
</xs:complexType><!--End personType -->
<xs:complexType name='nameType'>
<xs:sequence>
<xs:element name='given' minOccurs='1'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:pattern value='[A-Z]([a-z])*' />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name='family' minOccurs='1'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:pattern value='[A-Z]([a-z])*' />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType><!-- End nameType -->
<xs:complexType name='colourType'>
<xs:sequence>
<xs:element name='red' minOccurs='1' >
<xs:simpleType>
<xs:restriction base='xs:integer'>
<xs:minInclusive value='0' />
<xs:maxInclusive value='255' />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name='green' minOccurs='1' >
<xs:simpleType>
<xs:restriction base='xs:integer'>
<xs:minInclusive value='0' />
<xs:maxInclusive value='255' />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name='blue' minOccurs='1'>
<xs:simpleType>
<xs:restriction base='xs:integer'>
<xs:minInclusive value='0' />
<xs:maxInclusive value='255' />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType><!-- End colourType -->
</xs:schema>
[编辑] 在听取建议后,我做了以下更改。它可以解析,但不强制执行唯一属性。
<xs:complexType name='peopleType'>
<xs:sequence>
<xs:element name='person' type='personType' maxOccurs='unbounded'>
<xs:unique name="MyUserNameUniqueKey">
<xs:selector xpath="person" />
<xs:field xpath="@id" />
</xs:unique>
</xs:element>
</xs:sequence>
</xs:complexType><!-- End peopleType-->