∟Deriving New Simple Datatypes - "simpleType" Element
This section describes a tutorial example on how to define a simple datatype based on a built-in datatype by adding restriction facets.
Sometime, you want to modify a built-in datatype by adding some restrictions.
This can be done by using the Simple Type Definition Component.
For example, I want design a schema to validate an XML element called "age". I could use the built-in
datatype "nonNegativeInteger". But I want restrict the value to be less or equal to 150.
I can use the Simple Type Definition Component to modify "nonNegativeInteger" in this case.
Rule 1. The Simple Type Definition Component allows you to define a new simple datatype based on
an existing simple datatype, including any built-in datatype.
Rule 2. The XML representation of a Simple Type Definition Component is an "simpleType" element,
which must have one sub element of "restriction", "list", or "union". The sub element provides base datatypes
and modification details.
Rule 3. A "simpleType" element must have "name" attribute, if it is used to define a named datatype.
Here is the schema document, age.xsd. It defines a derived simple datatype "ageType", which is
derived from the built-in datatype "nonNegativeInteger" with a restriction of a maximum value.
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- age.xsd
- Copyright (c) 2013, HerongYang.com, All Rights Reserved.
-->
<!-- Using a derived simple datatype -->
<xs:element name="age" type="ageType"/>
<!-- Defining "ageType" based on "string" -->
<xs:simpleType name="ageType">
<xs:restriction base="xs:nonNegativeInteger">
<xs:maxInclusive value="150"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
Obviously, the following XML document, age_error.xml, does not conform the schema document, age.xsd:
<?xml version="1.0"?>
<age>200</age>
Here is the output of XsdSchemaValidator.java:
>java XsdSchemaValidator age.xsd age_error.xml
Error:
Line number: 2
Column number: 15
Message: cvc-maxInclusive-valid: Value '200' is not facet-valid
with respect to maxInclusive '150' for type 'ageType'.
Error:
Line number: 2
Column number: 15
Message: cvc-type.3.1.3: The value '200' of element 'age' is not
valid.
Failed with errors: 2
Note that the "maxInclusive" sub element is called a restriction "facet". Different built-in datatypes support
different sets of facets. For more information, read the built-in datatype chapter in this book.