将属性值限制为子属性(引用现有值)

时间:2011-04-27 10:28:47

标签: xml xsd

我有一个像这样的xml:

<userCredentials default="user1" >
    <userCredential username="user1" password="pwd" />
    <userCredential username="user2" password="pwd" />
    <userCredential username="user3" password="pwd" />
</userCredentials>

如何将属性default的值限制为//userCredential[@username]值中的一个?

在我的xsd架构下面:

<xs:complexType name="userCredential">
  <xs:attribute name="username" type="xs:string" use="required" />
  <xs:attribute name="password" type="xs:string" use="required" />
</xs:complexType>    

<xs:complexType name="userCredentials">
  <xs:sequence>
    <xs:element name="userCredential" type="tns:userCredential" minOccurs="1"
                maxOccurs="unbounded" />
  </xs:sequence>
  <xs:attribute name="default" use="required" >
      <xs:simpleType>
        <xs:restriction>
          <xs:pattern value="" />
        </xs:restriction>
      </xs:simpleType>
  </xs:attribute>        
</xs:complexType>  

1 个答案:

答案 0 :(得分:8)

这是完全可能的。下面是一个示例XSD,它强制执行块中所有用户名的唯一性,并且还要求default属性引用其中一个值:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="userCredentials" type="CredsType">

    <!-- ensure all user names are unique -->
    <xs:unique name="uniqueUserNames">
      <xs:selector xpath="userCredential"/>
      <xs:field xpath="@username"/>
    </xs:unique>

    <!-- ensure that the `default` attribute references existing username -->
    <xs:keyref name="defaultNameRef" refer="userNames">
      <xs:selector xpath="."/>
      <xs:field xpath="@default"/>
    </xs:keyref>
    <xs:key name="userNames">
      <xs:selector xpath="./userCredential"/>
      <xs:field xpath="@username"/>
    </xs:key>
  </xs:element>

  <xs:complexType name="CredsType">
    <xs:sequence>
      <xs:element name="userCredential" type="UserCredentialType"
                  maxOccurs="unbounded" />
    </xs:sequence>
    <xs:attribute name="default" type="xs:NCName" />
  </xs:complexType>

  <xs:complexType name="UserCredentialType">
    <xs:attribute name="username" type="xs:NCName"/>
    <xs:attribute name="password" type="xs:string"/>
  </xs:complexType>
</xs:schema>