在 xsd 单个字段上添加唯一约束

Adding a unique constraint on xsd single field

我有以下 xml.

 <Movies>
     <Title>
         <Platform>Hulu</Platform>
         <PlatformID>50019855</PlatformID>
         <UnixTimestamp>1431892827</UnixTimestamp>
     </Title>
     <Title>
         <Platform>Hulu</Platform>
         <PlatformID>50019855</PlatformID>
         <UnixTimestamp>1431892127</UnixTimestamp>
     </Title>
 </Movies>

然后我得到以下 xsd 来验证以上内容:

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

<xs:element name="Movies">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="Title" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="Platform" type="xs:string"/>
            <xs:element name="PlatformID" type="xs:string"/>
            <xs:element name="UnixTimestamp" type="xs:positiveInteger"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</xs:schema>

我如何添加一个唯一约束,使得 PlatformID 是一个唯一值,如果存在重复值,则验证失败,例如上面的 xml?

您需要将 xs:unique 约束放在 Movies 级别内,而不是 Title 级别内。如果它在 Title 级别内,它只会检查重复项 within 该节点:

XML

<Movies>
    <Title>
        <Platform>Hulu</Platform>
        <PlatformID>50019855</PlatformID>
        <UnixTimestamp>1431892827</UnixTimestamp>
    </Title>
    <Title>
        <Platform>Hulu</Platform>
        <PlatformID>50019855</PlatformID>
        <UnixTimestamp>1431892127</UnixTimestamp>
    </Title>
</Movies>

XSD

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Movies">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Title" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Platform" type="xs:string"/>
                            <xs:element name="PlatformID" type="xs:string" maxOccurs="unbounded"/>
                            <xs:element name="UnixTimestamp" type="xs:positiveInteger"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
        <xs:unique name="uniquePlatformID">
            <xs:selector xpath=".//Title/PlatformID"/>
            <xs:field xpath="."/>
        </xs:unique>
    </xs:element>
</xs:schema>