XSD 中的唯一元素未强制执行

Unique element in XSD is not enforced

我正在尝试为 XML 创建一个 XSD 并尝试强制执行 xs:unique 约束,但它没有强制执行约束。我究竟做错了什么?

这是XSD

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" 
           elementFormDefault="qualified"
           attributeFormDefault="unqualified"
           vc:minVersion="1.1"
           xmlns:o="http://www.osames.org/osamesorm">
  <xs:element name="DATA">
    <xs:annotation>
      <xs:documentation>Element that contain data</xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:sequence>
        <xs:element name="ACCOUNTID" type="xs:string"/>
        <xs:element name="CONTACTS" type="CONTACTType"/>
      </xs:sequence>
    </xs:complexType>
    <xs:unique name="unique-contactid">
      <xs:selector xpath="o:CONTACT"/>
      <xs:field xpath="@ID"/>
    </xs:unique>      
  </xs:element>
  <xs:element name="CONTACT">
    <xs:annotation>
      <xs:documentation>
        Contact Element contain one contact configuration/data
      </xs:documentation>
    </xs:annotation>
    <xs:complexType>
      <xs:all>
        <xs:element name="ID" type="xs:int"/>
        <xs:element name="TITLE" type="xs:string"/>
        <xs:element name="TYPE" type="xs:int"/>
        <xs:element name="CONTACTSTRING" type="xs:string"/>
      </xs:all>
    </xs:complexType>
  </xs:element>
  <xs:complexType name="CONTACTType">
    <xs:annotation>
      <xs:documentation>Complex Contect Type</xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:element ref="CONTACT"  minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

这里是一个 XML 应该是无效的,因为 2 个联系人具有相同的 ID (0)

<?xml version="1.0" encoding="UTF-8"?>
<DATA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="Untitled4.xsd">
    <ACCOUNTID>String</ACCOUNTID>
    <CONTACTS>
        <CONTACT>
            <ID>0</ID>
            <TITLE>String</TITLE>
            <TYPE>0</TYPE>
            <CONTACTSTRING>String</CONTACTSTRING>
        </CONTACT>
        <CONTACT>
            <ID>0</ID>
            <TITLE>String</TITLE>
            <TYPE>0</TYPE>
            <CONTACTSTRING>String</CONTACTSTRING>
        </CONTACT>
    </CONTACTS>
</DATA>

现在确定我做错了什么。

你的xs:unique声明,

    <xs:unique name="unique-contactid">
      <xs:selector xpath="o:CONTACT"/>
      <xs:field xpath="@ID"/>
    </xs:unique>                        

有几个问题需要您解决:

  1. CONTACT 不在命名空间中;删除 o:.
  2. CONTACTCONTACTS以内;将该元素添加到 XPath。
  3. @ID不是属性而是元素;更改为 ID.

那么,下面的xs:unique声明,

    <xs:unique name="unique-contactid">
        <xs:selector xpath="CONTACTS/CONTACT"/>
        <xs:field xpath="ID"/>
    </xs:unique>                    

将按要求工作。