Search code examples
regexxsdrestrictions

xsd:SimpleType: How to restrict attribute to specific values and regex values


I have an attribute that can be any string, but if it has starting and ending brackets "^[.*]$" - it must be only one of the following specific values:

"[EVENT]"  

and

"[PROTOCOL]"

So, "[EVENT]", "[PROTOCOL]", "SomeString" - are correct, but "[SomeString]" - isn't.

How can I achieve this?


Solution

  • I like @Burkart's use of separate xs:pattern elements better (+1), but I had this pending while awaiting clarification in comments ("[SomeString" without a closing bracket should be invalid), so I'll post it anyway in case anyone might find it useful. Read the regular expression as EVENT or PROTOCOL within brackets or any string that doesn't start or end with a bracket.

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="root">
        <xs:complexType>
          <xs:attribute name="attr">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:pattern value="\[(EVENT|PROTOCOL)\]|[^\[].*[^\]]"/>
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:complexType>
      </xs:element>
    </xs:schema>