Hsilgos
Hsilgos

Reputation: 91

XSD: Check that element with specific value presents

I have xml from XMPP core:

 <mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
   <mechanism>X-OAUTH2</mechanism>
   <mechanism>X-GOOGLE-TOKEN</mechanism>
   <mechanism>PLAIN</mechanism>
 </mechanisms

And i want to check that it contain one element PLAIN (and may be other, but PLAIN is required). I tried to do it with restrictions, but i can't make right rule. My attempt:

<xs:schema
       xmlns:xs='http://www.w3.org/2001/XMLSchema'
       targetNamespace='urn:ietf:params:xml:ns:xmpp-sasl'
       xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
       elementFormDefault='qualified'>
  <xs:element name='mechanisms'>
    <xs:complexType>
      <xs:all>
        <xs:element ref='mechanism' minOccurs='1' maxOccurs='1'/>
      </xs:all>
    </xs:complexType>
  </xs:element>
  <xs:element name="mechanism">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:pattern value="PLAIN" />
    </xs:restriction>
  </xs:simpleType>
  </xs:element>
</xs:schema>

Can anybody help me?

Upvotes: 2

Views: 2256

Answers (1)

Petru Gardea
Petru Gardea

Reputation: 21638

It depends on the XSD version you have access to; XSD 1.1 can do it out of the box, while XSD 1.0 alone cannot do the job.

Here is an XSD 1.1 schema example for your case:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:ietf:params:xml:ns:xmpp-sasl" xmlns="urn:ietf:params:xml:ns:xmpp-sasl" xmlns:tns="urn:ietf:params:xml:ns:xmpp-sasl" elementFormDefault="qualified">
    <xs:element name="mechanisms">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="mechanism" minOccurs="1" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:assert test="tns:mechanism[. eq 'PLAIN']" />
        </xs:complexType>
    </xs:element>
    <xs:element name="mechanism">
        <xs:simpleType>
            <xs:restriction base="xs:string"/>
        </xs:simpleType>
    </xs:element>
</xs:schema>

If mechanism's values are known, and you wish to explicitly validate them, then, in addition, you could use enumerations:

    <xs:element name="mechanism">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="X-OAUTH2"/>
                <xs:enumeration value="X-GOOGLE-TOKEN"/>
                <xs:enumeration value="PLAIN"/>                 
            </xs:restriction>
        </xs:simpleType>
    </xs:element>

Upvotes: 2

Related Questions