如何使用xsd:unique?

How to use xsd:unique?

我正在创建一个 XML 文件,我想在其中存储我对项目所做的更改,只是为了好玩。因此我写了一个小的 XML 模式。问题是我希望每个 Revisionid 属性都是唯一的。

所以我通过互联网和堆栈溢出进行了搜索,但我无法解决这个问题。我正在使用 Visual Studio 2015 - 不确定这是否会成为问题。

我使用的 XML 模式是:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
    <xs:element name="Revisions">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Revision" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Author" type="xs:string"/>
                            <xs:element name="Date" type="xs:date"/>
                            <xs:element name="Comments" type="xs:string"/>
                        </xs:sequence>
                        <xs:attribute name="id" type="xs:string" use="required"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
        <xs:unique name="Revision">
            <xs:annotation>
                <xs:documentation>
                    The id of each Revision element must be unique.
                </xs:documentation>
            </xs:annotation>
            <xs:selector xpath="Revision"/>
            <xs:field xpath="@id"/>
        </xs:unique>
    </xs:element>
</xs:schema>

以及我正在使用的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<Revisions xmlns="http://tempuri.org/XMLSchema.xsd">
    <Revision id="1">
        <Author>JP</Author>
        <Date>2014-07-09</Date>
        <Comments>Initial version</Comments>
    </Revision>
    <Revision id="2">
        <Author>JP</Author>
        <Date>2016-01-26</Date>
        <Comments>
            Created a RegistrationValidator class which uses regular expressions to check
            if usernames, passwords, email addresses, etc.. are in correct format
        </Comments>
    </Revision>
    <Revision id="3">
        <Author>JP</Author>
        <Date>2016-08-14</Date>
        <Comments>Created an XML schema which validates this XML file</Comments>
    </Revision>
    <Revision id="3">
        <Author>Test</Author>
        <Date>2016-08-14</Date>
        <Comments>dummy comments</Comments>
    </Revision>
</Revisions>

如您所见,我已将相同的 id 值分配给最后一个 Revision 标签,并且我没有从错误列表中收到任何错误、警告或消息。 有人知道我做错了什么吗?

你们非常亲密。只需将命名空间前缀 mstns 添加到 xs:selector/@xpath 即可解决问题:

<xs:unique name="Revision">
  <xs:annotation>
    <xs:documentation>
      The id of each Revision element must be unique.
    </xs:documentation>
  </xs:annotation>
  <xs:selector xpath="mstns:Revision"/>
  <xs:field xpath="@id"/>
</xs:unique>