在文档级别设置 XSD 重复约束

Set XSD duplicate constraint at document-level

我有以下 XML:

<Movies>
    <Title>
        <Platform>Hulu</Platform>
        <PlatformID>50019855</PlatformID> <!-- Reject xml based on duplicate PlatformID -->
        <UnixTimestamp>1431892827</UnixTimestamp>
    </Title>
    <Title>
        <Platform>Hulu</Platform>
        <PlatformID>50019855</PlatformID> <!-- Reject xml based on duplicate PlatformID -->
        <UnixTimestamp>1431892127</UnixTimestamp>
    </Title>
</Movies>

以下 XSD 有效,但我希望它拒绝它,因为 它有重复的 PlatformID.

<?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:unique name="uniquePlatformID">
        <xs:selector xpath=".//Title/PlatformID"/>
        <xs:field xpath="."/>
      </xs:unique>

      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>

这里正确的 XSD 是什么,要根据上面的重复 PlatformID 拒绝它?我目前使用的 XSD 有什么问题?我认为问题在于我正在尝试在 Title 节点内创建一个唯一约束,而我需要在 Movies/Title/PlatformID 级别的文档范围内创建它。

你很接近。只需将 xs:unique 向上移动成为根 Movies 元素定义的一部分,因为唯一性的范围旨在跨越整个文档(即在根元素内):

<?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"/>
      <xs:field xpath="PlatformID"/>
    </xs:unique>
  </xs:element>
</xs:schema>

然后你会得到一个错误,例如下面关于 PlatformID 的重复值的错误:

[Error] try.xml:11:42: cvc-identity-constraint.4.1: Duplicate unique value [50019855] declared for identity constraint "uniquePlatformID" of element "Movies".