2015-10-07 88 views
1

我试图通过不同元素类型的共享属性唯一性约束添加。所有这些元素共享一组通用属性,使用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元素的实例可以具有与secondType元素相同的id值。

mainType元素中定义的所有类型中,是否有使id属性唯一的方法?将单个元素名称设置为属性将意味着重大的代码更改和规范的隐式更改(我非常想不触发)。

回答

1

使用*(或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> 
+0

是的,这确实起作用。从中可以看出,XPath有助于抽象不同的元素类型。无论节点名称如何,“*”的意思是“所有孩子”。 –