What is the syntax to define the maxLength facet in XML Schema?

magdmartin picture magdmartin · Feb 19, 2013 · Viewed 33.1k times · Source

I'm trying to validate an XML schema with several tools, but I'm not getting a consistent message, depending on which tool I use. The following syntax seems to be the issue:

<xs:element name="Name" 
            minOccurs="1" 
            type ="xs:string" 
            maxLength = "125"/>

XML-Spy triggers an error whereas Notepad ++ (windows) and XML Copy Editor (Ubuntu) validate it. So is that syntax correct, or should I use this:

<xs:element name="name">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:minOccurs="1"/>
      <xs:maxLength = "125"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Answer

Petru Gardea picture Petru Gardea · Feb 19, 2013

This is what the syntax could look like:

<?xml version="1.0" encoding="utf-8" ?>
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) -->
<xs:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" xmlns="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="SomeContainer">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Name" minOccurs="0">
                    <xs:simpleType>
                        <xs:restriction base="xs:string">
                            <xs:maxLength value="125"/>
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>                   
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
  • minOccurs only goes to elements in a content model. It is not expected for global level elements.
  • A minOccurs="1" is superfluous. 1 is the default value, so you shouldn't have to specify it.
  • maxLength is a constraining facet associated with simple type restrictions.