如何使用<xs:unique>作为<xs:element>标记的子元素为属性指定唯一约束?

Mic*_*out 4 xsd unique-constraint

如果我在XSD中有以下元素规范,我可以将<xs:unique>约束添加为子项,<xs:element name="Parent">但我不能让它作为子项工作<xs:element name="Child">:

<xs:element name="Parent">
  <xs:complexType>
    <xs:element name="Child" minOccurs="0" maxOccurs="unbounded">
      <xs:complexType>
        <xs:attribute name="Key" type="xs:string" use="required" />
      </xs:complexType>

      <!-- Option A: insert unique constraint here with selector . -->

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

  <!-- Option B: insert unique constraint here with selector ./Child -->

</xs:element>
Run Code Online (Sandbox Code Playgroud)

这是作为孩子的唯一约束<xs:element name="Parent">:

<xs:unique name="ChildKey">
  <xs:selector xpath="./Child"/>
  <xs:field xpath="@Key" />
</xs:unique>
Run Code Online (Sandbox Code Playgroud)

但是这种独特的约束并不适合作为孩子<xs:element name="Child">:

<xs:unique name="ChildKey">
  <xs:selector xpath="."/>
  <xs:field xpath="@Key" />
</xs:unique>
Run Code Online (Sandbox Code Playgroud)

在第二种情况下是否需要更改选择器XPath?

Pet*_*dea 8

如果你考虑一下,选择器"." 将始终返回当前节点; 选择器为您提供仅包含一个节点的节点...因此,在仅包含一个节点的集合中,唯一性得到保证,因为具有给定名称的属性只能发生一次.这应该可以解释为什么你不能按照你认为应该的方式来实现它.

当您在父级别设置它时,它可以工作,因为您现在正在一组子节点中强制执行唯一性.

在数据库术语中,只能在表级别定义约束,例如您需要的约束.这就是它的样子(我稍微重写了XSD以获得良好的E/R).

XSD:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns:tns="http://tempuri.org/XMLSchema.xsd" xmlns="http://tempuri.org/XMLSchema.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Parent" type="Parent">
        <xs:unique name="ParentKey">
            <xs:selector xpath="tns:Child"/>
            <xs:field xpath="@Key"/>
        </xs:unique>
    </xs:element>
    <xs:complexType name="Parent">
        <xs:sequence>
            <xs:element name="Child" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                    <xs:attribute name="Key" type="xs:string" use="required"/>
                </xs:complexType>
                <xs:unique name="ChildKey">
                    <xs:selector xpath="."/>
                    <xs:field xpath="@Key"/>
                </xs:unique>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:schema>
Run Code Online (Sandbox Code Playgroud)

XSD图:

在此输入图像描述

等效的ADO.NET E/R:

在此输入图像描述

显示错误的XML:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<Parent xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/XMLSchema.xsd">
    <Child Key="Key1"/>
    <Child Key="Key1"/>
</Parent>
Run Code Online (Sandbox Code Playgroud)

错误信息:

Error occurred while loading [], line 5 position 3
There is a duplicate key sequence 'Key1' for the 'http://tempuri.org/XMLSchema.xsd:ParentKey' key or unique identity constraint.
Unique.xml is invalid.
Run Code Online (Sandbox Code Playgroud)