Search code examples
regexxmlxsdxsd-validationxml-validation

XSD identifier pattern


I'm trying to create an identifier of the form 1120XXXTP, where XXX is a code and TP is type: lc, lb, pr or ex

This is what i have so far

<xs:simpleType name="complex" >
 <xs:union>
  <xs:simpleType>
    <xs:restriction base="xs:string" >
      <xs:pattern value="[1][1][2][0][0-9]{3}" />
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:enumeration value="lc" />
      <xs:enumeration value="lb" />
      <xs:enumeration value="pr" />
      <xs:enumeration value="ex" />
    </xs:restriction>
  </xs:simpleType>
</xs:union>

This is an example in the XML of what the identifier should look like

<Classes>
    <CoursePartReference code="1120002lc">

I'm not able to set the pattern correctly.


Solution

  • You can match your identifier with a single regex pattern:

    <xs:pattern value="1120\d{3}(lc|lb|pr|ex)" />
    

    Altogether, then this XML,

    <CoursePartReference code="1120002lc">
    

    will be valid against this XSD,

    <?xml version="1.0"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="CoursePartReference">
        <xs:complexType>
          <xs:attribute name="code">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:pattern value="1120\d{3}(lc|lb|pr|ex)" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:complexType>
      </xs:element>
    </xs:schema>