Creating New Datatypes by Extension

Another way to create new datatypes is through extension. The most common example of this is adding an attribute to a simple type. The XML Schema spec says that simple types (xs:string, xs:integer, etc.) can’t have attributes. We can create a complex type that allows an element to have content of type xs:integer and have an attribute. Here’s how the schema looks:

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

  <xs:simpleType name="currency-type">
    <xs:restriction base="xs:string">
      <xs:enumeration value="USD"/>
      <xs:enumeration value="GBP"/>
      <xs:enumeration value="CNY"/>
      <xs:enumeration value="EUR"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:complexType name="price-type">
    <xs:simpleContent>
      <xs:extension base="xs:decimal">
        <xs:attribute name="currency" type="currency-type"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  
  <xs:element name="price" type="price-type"/>

</xs:schema>

Now we have an element whose content must be an xs:decimal, while it must also have an attribute named currency. Here’s a valid document for this schema:

<?xml version="1.0" encoding="utf-8"?>
<!-- extension.xml -->
<price
  xmlns="http://www.oreilly.com/xslt"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.oreilly.com/xslt extension.xsd"
  currency="USD">
438.92
</price>

If we change ...

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.