XSD Tutorials - Herong's Tutorial Examples - Version 5.11, by Dr. Herong Yang
Overriding the Base Datatype - xsi:type
This section describes a tutorial example on how to override the element base datatype with a derived datatype by using 'xsi:type'.
To override the base datatype when constructing an XML element, you need to remember the following rules:
1. In the schema, the derived datatype must be defined based on the base datatype.
2. Declare a new namespace prefix in the XML document called, "xsi", with a special attribute on the root element: "xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"". This is needed to provide the namespace prefix "xsi" for the next change.
3. In XML document, add the special attribute "xsi:type="derived-datatype"" to the element.
4. The element's attributes, text content, and child elements must conform to the specified the derived datatype.
Below is a tutorial sample XML document directory.xml that shows you how to override the base datatype with the special attribute "xsi:type":
<?xml version="1.0"?> <directory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <!-- directory.xml - Copyright (c) 2013, HerongYang.com, All Rights Reserved. --> <!-- using the base datatype --> <contact> <name>Herong Yang</name> </contact> <!-- using the derived datatype "phoneContactType" --> <contact xsi:type="phoneContactType"> <name>Traffic Hotline</name> <phone>1-866-MY-TRAFC</phone> </contact> <!-- using the derived datatype "emailContactType" --> <contact xsi:type="emailContactType"> <name>Suggestion Box</name> <email>suggestion@google.com</email> </contact> </directory>
Obviously, directory.xml will pass the schema validation as shown below:
>java XsdSchemaValidator directory.xsd directory.xml Passed.
Last update: 2013.
Table of Contents
XML Editor and Schema Processor - XMLPad
Java API for XML Processing - JAXP
JAXP - XML Schema (XSD) Validation
Xerces2 Java Parser - Java API of XML Parsers
Introduction of XSD Built-in Datatypes
"string" and Its Derived Datatypes
"decimal" and Its Derived Datatypes
"dateTime" and Its Related Datatypes
Miscellaneous Built-in Datatypes
Facets, Constraining Facets and Restriction Datatypes
"simpleType" - Defining Your Own Simple Datatypes
Identity-Constraints: unique, key and keyref
Assertion as Custom Validation Rules
XML Schema Location and Namespace in XML Documents
►Overriding Element Types in XML Documents
Overriding Element Type to Empty Content - nillable
Overriding Element Type to Empty Content - xsi:nil
Defining a Derived Datatype from a Base Datatype
►Overriding the Base Datatype - xsi:type
Overriding the Base Datatype - Errors