Search code examples
validationxsdrestrictioncomplextype

XSD restricting complex type element


I have a XSD definition which looks like this:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="ARTICLES">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="ARTICLE">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="NAME" type="xs:string" />
              <xs:element name="TYPE" type="xs:unsignedByte" />
              <xs:element name="LENGTH" type="xs:unsignedByte" />
              <xs:element name="WIDTH" type="xs:unsignedShort" />
              <xs:element name="HEIGHT" type="xs:unsignedShort" />
              <xs:element maxOccurs="unbounded" name="PRICELIST">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="SALESCONTRACT" type="xs:string" />
                    <xs:element name="PRICE" type="xs:decimal" />
                    <xs:element name="VAT" type="xs:unsignedByte" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

An XML can contain a collection of ATRICLES and each ARTICLE can have 1 or more PRICELIST entries

Now I would like to take an element and restrict the value entries. i.e. With a regex or numbers only or in length. With simpletype I found lots of examples that work with a pattern tag. How would this work with complex types?

Regards,

Rick


Solution

  • You can simply apply all of those examples you've found using xs:simpleType to any of the parts of ARTICLE that you wish to further constrain. For example, to limit NAME to be of maximum length of 32 characters:

              <xs:element name="NAME">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:maxLength value="32"/>
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>