pexxxy
pexxxy

Reputation: 509

Xml schema, how to make sure one element exists with a specific attribute value

How do I enforce the existing of an element with a specific attribute value in the XML?

For example:

<events>
  <event type="system" desc="this is a system event"/>
  <event type="bla1" desc="this is bla1 event"/>
  <event type="bla2" desc="this is bla2 event"/>
</events>

I need a rule to make sure the event element with type attribute = 'system' exists (once). All other event elements are optional;

Upvotes: 1

Views: 6607

Answers (1)

kjhughes
kjhughes

Reputation: 111630

If you're using XML Schema 1.0, you cannot express the constraint directly. You could do it outside of XML Schema 1.0 via Schematron or XSLT directly.

If you're using XML Schema 1.1, you can specify co-occurrence constraints via xs:assert:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           version="1.0">
  <xs:element name="events">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="event" minOccurs="1" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="type" type="xs:string"/>
            <xs:attribute name="desc" type="xs:string"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:assert test="count(event[@type = 'system']) = 1"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

Upvotes: 4

Related Questions