Search code examples
xmlxsdxsd-validationxml-validation

Restricting values in XML Schema


I have an XSD with two elements, name and color. Would like to restrict length of names to 5. Getting an error:

simpleType element not supported in this context.

As I understand these are custom types that can used in declaring elements in a schema file.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="fruits">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" />
                    <xs:simpleType>
                        <xs:restriction base="xs:name">
                            <xs:length="5">
                        </xs:restriction>
                    </xs:simpleType>
                </xs:/element>
                <xs:element name="color" type="xs:string" minOccurs="0" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XML:

<?xml version="1.0" encoding="UTF-8"?>
<fruits 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="simplexsd2.xsd">
    <name>Apple</name>
</fruits>

Solution

  • Among the multiple syntax errors to be fixed in your XSD are,

    • prematurely closed xs:element element.
    • malformed xs:length element.
    • malformed close tags.

    Here is your XSD updated to be well-formed and to support your intended validation of name elements to have string values restricted to length 5:

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="fruits">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="name">
              <xs:simpleType>
                <xs:restriction base="xs:string">
                  <xs:length value="5"/>
                </xs:restriction>
              </xs:simpleType>
            </xs:element>
            <xs:element name="color" type="xs:string" minOccurs="0" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>