XSD required strings

2008-03-09 @ 18:49#

setting up an XML Schema(XSD) document is pretty simple. here's an example that has all required fields:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="form">
    <xs:complexType>
      <xs:all>
        <xs:element name="firstname" type="xs:string" minOccurs="1" maxOccurs="1"/>
        <xs:element name="lastname" type="xs:string"  minOccurs="1" maxOccurs="1"/>
      </xs:all>
    </xs:complexType>
  </xs:element>
</xs:schema>

you might think the following XML document would fail validation, but it does not:

<form>
  <firstname></firstname>
  <lastname></lastname>
</form>

that's because an empty element will be interpreted as an empty string. it's a string!

so you need a bit more in the schema to make it all work, you need to set up a required length restriction on the string elements. i do it like this:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="form">
    <xs:complexType>
      <xs:all>
        <xs:element name="firstname" type="requiredStringType" minOccurs="1" maxOccurs="1"/>
        <xs:element name="lastname" type="requiredStringType"  minOccurs="1" maxOccurs="1"/>
      </xs:all>
    </xs:complexType>
  </xs:element>
  <!-- required string -->
  <xs:simpleType name="requiredStringType">
    <xs:restriction base="xs:string">
      <xs:minLength value="1"/>
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

now the previous XML document will fail with the following message:

The 'firstname' element is invalid - The value '' is invalid according to its datatype 'requiredStringType' - The actual length is less than the MinLength value.

ain't XSD grand?

code