不同元素类型之间的唯一属性

Unique attribute among different element types

我正在尝试对不同元素类型共享的属性添加唯一性约束。所有这些元素共享一组公共属性,使用 attributeGroup.

定义
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:attributeGroup name="commonAttributes">
    <xs:attribute name="id" type="xs:string" use="required" />
    <xs:attribute name="displayName" type="xs:string" />
  </xs:attributeGroup>

  ...
  <xs:element name="mainType" minOccurs="0">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="firstType" minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attributeGroup ref="commonAttributes"></xs:attributeGroup>
          </xs:complexType>
        </xs:element>
        <xs:element name="secondType" minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attributeGroup ref="commonAttributes"></xs:attributeGroup>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  ...
</xs:schema>

基本上,firstTypesecondType 元素都定义了 id 属性,该属性需要在每个 mainType 实例中具有唯一值。据我了解,unique 约束不能设置在 xs:attributeGroup 内。在 firstTypesecondType 元素上设置此约束显然只适用于该类型的其他元素,这意味着 firstType 元素的实例可以具有相同的 id 值作为 secondType 元素。

有没有办法使 id 属性在 mainType 元素内定义的所有类型中是唯一的?拥有一个并将当前元素名称设置为属性将意味着重大的代码更改和规范的隐式更改(我非常希望不要触发)。

使用 *(或 firstType | secondType)作为 XPath 表达式。

试试这个:

        <xs:unique name="uniqueAttr">
            <xs:selector xpath="*"></xs:selector>
            <xs:field xpath="@id"></xs:field>
        </xs:unique>

mainType 元素中使用上面的代码,如下所示:

 <xs:element name="mainType" >
        <xs:complexType>
            <xs:sequence>
                <xs:element name="firstType" minOccurs="0" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:attributeGroup ref="commonAttributes"></xs:attributeGroup>
                    </xs:complexType>
                </xs:element>
                <xs:element name="secondType" minOccurs="0" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:attributeGroup ref="commonAttributes"></xs:attributeGroup>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
        <xs:unique name="uniqueAttr">
            <xs:selector xpath="*"></xs:selector>
            <xs:field xpath="@id"></xs:field>
        </xs:unique>
    </xs:element>