XML validation issue

Bhushan picture Bhushan · Apr 2, 2012 · Viewed 8.3k times · Source

I am trying to validate an XML against an XSD using 'xmllint' command of Unix. The problem I am facing is this:

In the XSD, the field "state" is specified as follows:

  <xs:element name="state">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:maxLength value="2"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:element>

Notice the <xs:maxLength value="2"/>

And in the XML, the state field comes as this:

TYPE 1:

        <state>
            FL
        </state>

OR

TYPE 2:

<state>FL</state>

For TYPE 1, I get the following error:

test.xml:243: element state: Schemas validity error : Element 'state': [facet 'maxLength'] The value has a length of '32'; this exceeds the allowed maximum length of '2'.
test.xml:243: element state: Schemas validity error : Element 'state': '
                FL
            ' is not a valid value of the local atomic type.

And for TYPE 2, it valides properly without any errors.

So, basically the white-spaces in the formatted-XML are causing problems. I want the XML to pass for both the cases. Is there any way to do this with or without xmllint?

Thanks a lot.

Answer

Petru Gardea picture Petru Gardea · Apr 3, 2012

Try this schema, QTAssistant validates your XML, I am sure your validator should, too:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="state">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:whiteSpace value="collapse"/>
                <xs:maxLength value="2"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
</xs:schema>

The trick is the whiteSpace clause.