Creating New Datatypes by Restriction

A common way to create new datatypes is to restrict the values of another datatype. We’ll look at three approaches: ranges, enumerations, and regular expressions.

For our first example, we’ll use a range to define a datatype called age based on xs:integer. We would like for the age datatype to have a value between 0 and 130. (We’re being optimistic about longevity here.) Here’s how we define a range of valid values:

<?xml version="1.0" encoding="UTF-8"?>
<!-- person1.xsd -->
<xs:schema 
  xmlns="http://www.oreilly.com/xslt"
  targetNamespace="http://www.oreilly.com/xslt"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="person">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="name"/>
        <xs:element ref="age"/>
      </xs:sequence>
      <xs:attribute name="eyeColor" type="xs:string"/>
    </xs:complexType>
  </xs:element>

  <xs:element name="name" type="xs:string"/>

  <xs:simpleType name="age-type">
    <xs:restriction base="xs:integer">
      <xs:minInclusive value="0"/>
      <xs:maxInclusive value="130"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:element name="age" type="age-type"/>

</xs:schema>

We’ve defined a new datatype, age-type, and we’ve used it as the datatype for the element <age>. Here’s a valid document for this schema:

<?xml version="1.0" encoding="utf-8"?>
<!-- person1.xml --> <person xmlns="http://www.oreilly.com/xslt" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.oreilly.com/xslt person1.xsd" eyeColor="brown"> <name>Doug ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.