1

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;

4

1 回答 1

4

如果您使用的是 XML Schema 1.0,则不能直接表达约束。您可以通过 Schematron 或 XSLT 在 XML Schema 1.0 之外直接进行。

如果您使用的是 XML Schema 1.1,则可以通过以下方式指定共现约束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>
于 2013-10-23T15:32:02.623 回答