开发者

XSD: Same element, different attributes

开发者 https://www.devze.com 2023-01-26 14:21 出处:网络
What I need to do is to validate this piece of xml: <token type=\"email\">qwqe12e12e1</token>

What I need to do is to validate this piece of xml:

<token type="email">qwqe12e12e1</token>
<token type="mobile">12e12313121w开发者_StackOverflow中文版</token>

I know how to validate such element with attribute and content but my question is how to prevent token of type e.g. email occur more than once? I need both tokens but every single token can occur only once.


The <xsd:unique> element is your friend.

See http://msdn.microsoft.com/en-us/library/ms256146.aspx


Given the following XML sample:

<tokens>
  <token type="email">qwqe12e12e1</token>
  <token type="mobile">12e12313121w</token>
  <token type="mobile">1234</token>
</tokens>

and the following XSD:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="tokens">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="token" maxOccurs="unbounded" />
      </xs:sequence>
    </xs:complexType>
    <!-- token[type] to only occur once -->
    <xs:unique name="type">
      <xs:selector xpath="token" />
      <xs:field xpath="@type" />
    </xs:unique>
  </xs:element>

  <xs:element name="token">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute name="type" use="required">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="email"/>
                <xs:enumeration value="mobile"/>
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

The validation will fail on the second "mobile" token type.

When the second "mobile" token type is removed from the input XML, the validation will succeed.

0

精彩评论

暂无评论...
验证码 换一张
取 消