XML Schema Part 0: Primer Second Edition code { font-family: monospace; }
div.constraint, div.issue, div.note, div.notice { margin-left: 2em; }
ol.enumar { list-style-type: decimal; } ol.enumla { list-style-type: lower-alpha; } ol.enumlr { list-style-type: lower-roman; } ol.enumua { list-style-type: upper-alpha; } ol.enumur { list-style-type: upper-roman; }
div.exampleInner pre { margin-left: 1em; margin-top: 0em; margin-bottom: 0em} div.exampleOuter {border: 4px double gray; margin: 0em; padding: 0em} div.exampleInner { background-color: #d5dee3; border-top-width: 4px; border-top-style: double; border-top-color: #d3d3d3; border-bottom-width: 4px; border-bottom-style: double; border-bottom-color: #d3d3d3; padding: 4px; margin: 0em } div.exampleWrapper { margin: 4px } div.exampleHeader { font-weight: bold; margin: 4px}
img { color: white; border: none } span.nav { float: right} span.arrow { font-style: normal; font-weight: bold } code { font-family: monospace; font-size: 100%} span.propdef { font-weight: bold; font-family: monospace } span.termdef {color: #850021} a.termref:visited, a.termref:link {font-family: sans-serif; font-style: normal; color: black; text-decoration: none } a.eltref:visited, a.eltref:link { font-family: sans-serif; color: black; text-decoration: none } a.propref:visited, a.xpropref:visited, a.propref:link, a.xpropref:link { color: black; text-decoration: none; font-family: sans-serif } dl.props, dl.psvi {margin-bottom: .5em; margin-top: 0em} div.toc1 {margin-left: 5ex} div.toc2 {margin-left: 2ex} div.tocLine{margin: 0em; text-indent: -6ex} h3.withToc {margin-bottom: 0em} div.constraintnote { margin-top: 1em } div.constraint { margin-left: 1em; } div.constraintlist { margin-left: 1em; margin-bottom: 0em } div.clnumber { text-indent: -1em; margin-top: 0em; margin-bottom: 0em } div.schemaComp { border: 4px double gray; margin: 0em 1em; padding: 0em } div.compHeader { margin: 4px; font-weight: bold } span.schemaComp { color: #A52A2A } div.compBody { border-top-width: 4px; border-top-style: double; border-top-color: #d3d3d3; padding: 4px ; margin: 0em} div.psviDef { border: 4px double gray; margin: 1em 1em; padding: 0em } div.psviHeader { margin: 4px; font-weight: bold } span.psviDef { color: #A52A2A } div.psviBody { border-top-width: 4px; border-top-style: double; border-top-color: #d3d3d3; padding: 4px ; margin: 0em} div.reprdef { border: 4px double gray; margin: 0em 1em; padding: 0em } div.reprHeader { margin: 4px; font-weight: bold } span.reprdef { color: #A52A2A } div.reprBody, div.reprcomp, div.reprdep { border-top-width: 4px; border-top-style: double; border-top-color: #d3d3d3; padding: 4px ; margin: 0em} table.reprcomp { margin-bottom: -.5em} p.element-syntax-1 { font-family: monospace; margin-top: 0em; margin-bottom: .5em } p.element-syntax { font-family: monospace; border-top-width: 1px; border-top-style: solid; border-top-color: #d3d3d3; padding: 4px ; margin: 0em} div.exampleInner pre { margin-left: 1em; margin-top: 0em; margin-bottom: 0em} div.exampleOuter {border: 4px double gray; margin: 0em; padding: 0em} div.exampleInner { background-color: #d5dee3; border-top-width: 4px; border-top-style: double; border-top-color: #d3d3d3; border-bottom-width: 4px; border-bottom-style: double; border-bottom-color: #d3d3d3; padding: 4px; margin: 0em } div.exampleWrapper { margin: 4px } div.exampleHeader { font-weight: bold; margin: 4px} span.edtext { color: red } table.restricts { margin-top: 1em; margin-bottom: 1em; margin-left: -2em} table.restricts th { margin-left: 0em } table.ubc td, table.ubc th { font-size: smaller } table.dtdemo th { text-align: center; background-color: #d5dee3} table.dtdemo pre { margin-left: 0em; margin-bottom: 0em} table.dtdemo td {background-color: #bedce6} table.scrap {background-color: #f5dcb3} img { color: white; border: none } span.nav { float: right} span.arrow { font-style: normal; font-weight: bold } This version: http://www.w3.org/TR/2004/REC-xmlschema-0-20041028/ Latest version: http://www.w3.org/TR/xmlschema-0/ Previous version: http://www.w3.org/TR/2004/PER-xmlschema-0-20040318/ Editors: David C. Fallside, IBM <[email protected]> Priscilla Walmsley <[email protected]> Please refer to the errata This document is also available in these non-normative formats: XML XHTML with visible change markup translations Copyright W3C ® MIT ERCIM Keio liability trademark document use XML Schema Part 0: Primer is a non-normative document intended to provide an easily readable description of the XML Schema facilities, and is oriented towards quickly understanding how to create schemas using the XML Schema language. XML Schema Part 1: Structures XML Schema Part 2: Datatypes This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index This is a W3C Recommendation This document has been produced by the W3C XML Schema Working Group XML Activity XML Schema Requirements This document was produced under the 24 January 2002 Current Patent Practice (CPP) W3C Patent Policy Transition Procedure public list of patent disclosures section 6 of the W3C Patent Policy The English version of this specification is the only normative version. Information about translations of this document is available at http://www.w3.org/2001/05/xmlschema-translations This second edition is not first edition http://www.w3.org/2001/05/xmlschema-errata The errata list for this second edition is available at http://www.w3.org/2004/03/xmlschema-errata Please report errors in this document to [email protected] archive 1 Introduction Basic Concepts: The Purchase Order The Purchase Order Schema Complex Type Definitions, Element & Attribute Declarations Simple Types Anonymous Type Definitions Element Content Annotations Building Content Models Attribute Groups Nil Values Advanced Concepts I: Namespaces, Schemas & Qualification Target Namespaces & Unqualified Locals Qualified Locals Global vs. Local Declarations Undeclared Target Namespaces Advanced Concepts II: The International Purchase Order A Schema in Multiple Documents Deriving Types by Extension Using Derived Types in Instance Documents Deriving Complex Types by Restriction Redefining Types & Groups Substitution Groups Abstract Elements and Types Controlling the Creation & Use of Derived Types Advanced Concepts III: The Quarterly Report Specifying Uniqueness Defining Keys & their References XML Schema Constraints vs. XML 1.0 ID Attributes Importing Types Any Element, Any Attribute schemaLocation Conformance A Acknowledgements Simple Types & their Facets Using Entities Regular Expressions Index XML Schema Elements XML Schema Attributes This document, XML Schema Part 0: Primer, provides an easily approachable description of the XML Schema definition language, and should be used alongside the formal descriptions of the language contained in Parts 1 2 XML 1.0 Namespaces in XML Basic Concepts: The Purchase Order (§2) Advanced Concepts I: Namespaces, Schemas & Qualification (§3) Advanced Concepts II: The International Purchase Order (§4) Advanced Concepts III: The Quarterly Report (§5) In addition to the sections just described, the primer contains a number of appendices that provide detailed reference information on simple types and a regular expression language. The primer is a non-normative document, which means that it does not provide a definitive (from the W3C's point of view) specification of the XML Schema language. The examples and other explanatory material in this document are provided to help you understand XML Schema, but they may not always provide definitive answers. In such cases, you will need to refer to the XML Schema specification, and to help you do this, we provide many links pointing to the relevant parts of the specification. More specifically, XML Schema items mentioned in the primer text are linked to an index [ Index (§E) table The purpose of a schema is to define a class of XML documents, and so the term "instance document" is often used to describe an XML document that conforms to a particular schema. In fact, neither instances nor schemas need to exist as documents per se Let us start by considering an instance document in a file called po.xml Example The Purchase Order, po.xml <?xml version="1.0"?> <purchaseOrder orderDate="1999-10-20"> <shipTo country="US"> <name>Alice Smith</name> <street>123 Maple Street</street> <city>Mill Valley</city> <state>CA</state> <zip>90952</zip> </shipTo> <billTo country="US"> <name>Robert Smith</name> <street>8 Oak Avenue</street> <city>Old Town</city> <state>PA</state> <zip>95819</zip> </billTo> <comment>Hurry, my lawn is going wild<!/comment> <items> <item partNum="872-AA"> <productName>Lawnmower</productName> <quantity>1</quantity> <USPrice>148.95</USPrice> <comment>Confirm this is electric</comment> </item> <item partNum="926-AA"> <productName>Baby Monitor</productName> <quantity>1</quantity> <USPrice>39.98</USPrice> <shipDate>1999-05-21</shipDate> </item> </items> </purchaseOrder> The purchase order consists of a main element, purchaseOrder shipTo billTo comment items comment USPrice The complex types in the instance document, and some of the simple types, are defined in the schema for purchase orders. The other simple types are defined as part of XML Schema's repertoire of built-in simple types. Before going on to examine the purchase order schema, we digress briefly to mention the association between the instance document and the purchase order schema. As you can see by inspecting the instance document, the purchase order schema is not mentioned. An instance is not actually required to reference a schema, and although many will, we have chosen to keep this first section simple, and to assume that any processor of the instance document can obtain the purchase order schema without any information from the instance document. In later sections, we will introduce explicit mechanisms for associating instances and schemas. The purchase order schema is contained in the file po.xsd Example The Purchase Order Schema, po.xsd <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:annotation> <xsd:documentation xml:lang="en"> Purchase order schema for Example.com. Copyright 2000 Example.com. All rights reserved. </xsd:documentation> </xsd:annotation>
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
<xsd:element name="comment" type="xsd:string"/>
<xsd:complexType name="PurchaseOrderType"> <xsd:sequence> <xsd:element name="shipTo" type="USAddress"/> <xsd:element name="billTo" type="USAddress"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="items" type="Items"/> </xsd:sequence> <xsd:attribute name="orderDate" type="xsd:date"/> </xsd:complexType>
<xsd:complexType name="USAddress"> <xsd:sequence> <xsd:element name="name" type="xsd:string"/> <xsd:element name="street" type="xsd:string"/> <xsd:element name="city" type="xsd:string"/> <xsd:element name="state" type="xsd:string"/> <xsd:element name="zip" type="xsd:decimal"/> </xsd:sequence> <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/> </xsd:complexType>
<xsd:complexType name="Items"> <xsd:sequence> <xsd:element name="item" minOccurs="0" maxOccurs="unbounded"> <xsd:complexType> <xsd:sequence> <xsd:element name="productName" type="xsd:string"/> <xsd:element name="quantity"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="100"/> </xsd:restriction> </xsd:simpleType> </xsd:element> <xsd:element name="USPrice" type="xsd:decimal"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/> </xsd:sequence> <xsd:attribute name="partNum" type="SKU" use="required"/> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType>
<!-- Stock Keeping Unit, a code for identifying products --> <xsd:simpleType name="SKU"> <xsd:restriction base="xsd:string"> <xsd:pattern value="\d{3}-[A-Z]{2}"/> </xsd:restriction> </xsd:simpleType>
</xsd:schema> The purchase order schema consists of a schema element complexType simpleType Each of the elements in the schema has a prefix xsd: xmlns:xsd="http://www.w3.org/2001/XMLSchema" schema xsd: xsd: string simpleType 2.2.1 Occurrence Constraints Global Elements & Attributes Naming Conflicts In XML Schema, there is a basic difference between complex types which allow elements in their content and may carry attributes, and simple types which cannot have element content and cannot carry attributes. There is also a major distinction between definitions which create new types (both simple and complex), and declarations which enable elements and attributes with specific names and types (both simple and complex) to appear in document instances. In this section, we focus on defining complex types and declaring the elements and attributes that appear within them. New complex types are defined using the complexType element attribute USAddress USAddress Example Defining the USAddress Type <xsd:complexType name="USAddress" > <xsd:sequence> <xsd:element name="name" type="xsd:string"/> <xsd:element name="street" type="xsd:string"/> <xsd:element name="city" type="xsd:string"/> <xsd:element name="state" type="xsd:string"/> <xsd:element name="zip" type="xsd:decimal"/> </xsd:sequence> <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/> </xsd:complexType> The consequence of this definition is that any element appearing in an instance whose type is declared to be USAddress shipTo po.xml name street city state zip name USAddress country US The USAddress string decimal NMTOKEN PurchaseOrderType USAddress type Example Defining PurchaseOrderType <xsd:complexType name="PurchaseOrderType"> <xsd:sequence> <xsd:element name="shipTo" type="USAddress"/> <xsd:element name="billTo" type="USAddress"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="items" type="Items"/> </xsd:sequence> <xsd:attribute name="orderDate" type="xsd:date"/> </xsd:complexType> In defining PurchaseOrderType shipTo billTo USAddress po.xml PurchaseOrderType shipTo billTo, name street city state zip USAddress shipTo billTo country USAddress The PurchaseOrderType orderDate country The element declarations we have described so far have each associated a name with an existing type definition. Sometimes it is preferable to use an existing element rather than declare a new element, for example: Example <xsd:element ref="comment" minOccurs="0"/> This declaration references an existing element, comment ref schema comment string The comment PurchaseOrderType minOccurs minOccurs maxOccurs unbounded minOccurs maxOccurs comment maxOccurs minOccurs maxOccurs maxOccurs minOccurs Attributes may appear once or not at all, but no other number of times, and so the syntax for specifying occurrences of attributes is different than the syntax for elements. In particular, attributes can be declared with a use required partNum po.xsd optional prohibited Default values of both attributes and elements are declared using the default default optional use The schema processor treats defaulted elements slightly differently. When an element is declared with a default value, the value of the element is whatever value appears as the element's content in the instance document; if the element appears without any content, the schema processor provides the element with a value equal to that of the default The fixed po.xsd country fixed US country use optional US country US fixed default The values of the attributes used in element and attribute declarations to constrain their occurrences are summarized in Table 1 Table 1. Occurrence Constraints for Elements and Attributes Elements ( minOccurs maxOccurs fixed default Attributes use fixed default Notes (1, 1) -, - required, -, - element/attribute must appear once, it may have any value (1, 1) 37, - required, 37, - element/attribute must appear once, its value must be 37 (2, unbounded) 37, - n/a element must appear twice or more, its value must be 37; in general, minOccurs maxOccurs maxOccurs (0, 1) -, - optional, -, - element/attribute may appear once, it may have any value (0, 1) 37, - n/a element may appear once, if it does not appear it is not provided; if it does appear and it is empty, its value is 37; if it does appear and it is not empty, its value must be 37 n/a optional, 37, - attribute may appear once, if it does appear its value must be 37, if it does not appear its value is 37 (0, 1) -, 37 n/a element may appear once; if it does not appear it is not provided; if it does appear and it is empty, its value is 37; otherwise its value is that given n/a optional, -, 37 attribute may appear once; if it does not appear its value is 37, otherwise its value is that given (0, 2) -, 37 n/a element may appear once, twice, or not at all; if the element does not appear it is not provided; if it does appear and it is empty, its value is 37; otherwise its value is that given; in general, minOccurs maxOccurs maxOccurs (0, 0) -, - prohibited, -, - element/attribute must not appear Note that neither minOccurs maxOccurs use Global elements, and global attributes, are created by declarations that appear as the children of the schema ref comment po.xml shipTo billTo items comment The declaration of a global element also enables the element to appear at the top-level of an instance document. Hence purchaseOrder po.xsd po.xml comment po.xml There are a number of caveats concerning the use of global elements and attributes. One caveat is that global declarations cannot contain references; global declarations must identify simple and complex types directly. Put concretely, global declarations cannot contain the ref type anonymous type definition minOccurs maxOccurs use We have now described how to define new complex types (e.g. PurchaseOrderType purchaseOrder orderDate Here are some examples to illustrate when same names cause problems. If the two things are both types, say we define a complex type called USStates and a simple type called USStates, there is a conflict. If the two things are a type and an element or attribute, say we define a complex type called USAddress and we declare an element called USAddress, there is no conflict. If the two things are elements within different types (i.e. not global elements), say we declare one element called name as part of the USAddress type and a second element called name as part of the Item type, there is no conflict. (Such elements are sometimes called local element declarations.) Finally, if the two things are both types and you define one and XML Schema has defined the other, say you define a simple type called decimal, there is no conflict. The reason for the apparent contradiction in the last example is that the two types belong to different namespaces. We explore the use of namespaces in schema in a later section. 2.3.1 List Types Union Types The purchase order schema declares several elements and attributes that have simple types. Some of these simple types, such as string decimal partNum SKU string Table 2 Table 2. Simple Types Built In to XML Schema Simple Type Examples (delimited by commas) Notes string Confirm this is electric normalizedString Confirm this is electric see (3) token Confirm this is electric see (4) base64Binary GpM7 hexBinary 0FB7 integer ...-1, 0, 1, ... see (2) positiveInteger 1, 2, ... see (2) negativeInteger ... -2, -1 see (2) nonNegativeInteger 0, 1, 2, ... see (2) nonPositiveInteger ... -2, -1, 0 see (2) long -9223372036854775808, ... -1, 0, 1, ... 9223372036854775807 see (2) unsignedLong 0, 1, ... 18446744073709551615 see (2) int -2147483648, ... -1, 0, 1, ... 2147483647 see (2) unsignedInt 0, 1, ...4294967295 see (2) short -32768, ... -1, 0, 1, ... 32767 see (2) unsignedShort 0, 1, ... 65535 see (2) byte -128, ...-1, 0, 1, ... 127 see (2) unsignedByte 0, 1, ... 255 see (2) decimal -1.23, 0, 123.4, 1000.00 see (2) float -INF, -1E4, -0, 0, 12.78E-2, 12, INF, NaN equivalent to single-precision 32-bit floating point, NaN is "not a number", see (2) double -INF, -1E4, -0, 0, 12.78E-2, 12, INF, NaN equivalent to double-precision 64-bit floating point, see (2) boolean true, false, 1, 0 duration P1Y2M3DT10H30M12.3S 1 year, 2 months, 3 days, 10 hours, 30 minutes, and 12.3 seconds dateTime 1999-05-31T13:20:00.000-05:00 May 31st 1999 at 1.20pm Eastern Standard Time which is 5 hours behind Co-Ordinated Universal Time, see (2) date 1999-05-31 see (2) time 13:20:00.000, 13:20:00.000-05:00 see (2) gYear 1999 1999, see (2) (5) gYearMonth 1999-02 the month of February 1999, regardless of the number of days, see (2) (5) gMonth --05 May, see (2) (5) gMonthDay --05-31 every May 31st, see (2) (5) gDay ---31 the 31st day, see (2) (5) Name shipTo XML 1.0 Name type QName po:USAddress XML Namespace QName NCName USAddress XML Namespace NCName, i.e. a QName without the prefix and colon anyURI http://www.example.com/, http://www.example.com/doc.html#ID5 language en-GB, en-US, fr valid values for xml:lang as defined in XML 1.0 ID XML 1.0 ID attribute type, see (1) IDREF XML 1.0 IDREF attribute type, see (1) IDREFS XML 1.0 IDREFS attribute type, see (1) ENTITY XML 1.0 ENTITY attribute type, see (1) ENTITIES XML 1.0 ENTITIES attribute type, see (1) NOTATION XML 1.0 NOTATION attribute type, see (1) NMTOKEN US, Brésil XML 1.0 NMTOKEN attribute type, see (1) NMTOKENS US UK, Brésil Canada Mexique XML 1.0 NMTOKENS attribute type, i.e. a whitespace separated list of NMTOKEN's, see (1) Notes: (1) To retain compatibility between XML Schema and XML 1.0 DTDs, the simple types ID, IDREF, IDREFS, ENTITY, ENTITIES, NOTATION, NMTOKEN, NMTOKENS should only be used in attributes. (2) A value of this type can be represented by more than one lexical format, e.g. 100 and 1.0E2 are both valid float formats representing "one hundred". However, rules have been established for this type that define a canonical lexical format, see XML Schema Part 2 New simple types are defined by deriving them from existing simple types (built-in's and derived). In particular, we can derive a new simple type by restricting an existing simple type, in other words, the legal range of values for the new type are a subset of the existing type's range of values. We use the simpleType restriction Appendix B Suppose we wish to create a new type of integer called myInteger integer myInteger integer minInclusive maxInclusive Example Defining myInteger, Range 10000-99999 <xsd:simpleType name="myInteger"> <xsd:restriction base="xsd:integer"> <xsd:minInclusive value="10000"/> <xsd:maxInclusive value="99999"/> </xsd:restriction> </xsd:simpleType> The example shows one particular combination of a base type and two facets used to define myInteger Appendix B The purchase order schema contains another, more elaborate, example of a simple type definition. A new simple type called SKU string SKU pattern \d{3}-[A-Z]{2} Example Defining the Simple Type "SKU" <xsd:simpleType name="SKU"> <xsd:restriction base="xsd:string"> <xsd:pattern value="\d{3}-[A-Z]{2}"/> </xsd:restriction> </xsd:simpleType> This regular expression language is described more fully in Appendix D XML Schema defines twelve facets which are listed in Appendix B enumeration boolean enumeration enumeration USState string Example Using the Enumeration Facet <xsd:simpleType name="USState"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="AK"/> <xsd:enumeration value="AL"/> <xsd:enumeration value="AR"/> <!-- and so on ... --> </xsd:restriction> </xsd:simpleType> USState string state state state billTo shipTo AK AL AR XML Schema has the concept of a list type, in addition to the so-called atomic types that constitute most of the types listed in Table 2 NMTOKEN US US NMTOKENS NMTOKEN NMTOKENS IDREFS ENTITIES In addition to using the built-in list types, you can create new list types by derivation from existing atomic types. (You cannot create list types from existing list types, nor from complex types.) For example, to create a list of myInteger Example Creating a List of myInteger's <xsd:simpleType name="listOfMyIntType"> <xsd:list itemType="myInteger"/> </xsd:simpleType> And an element in an instance document whose content conforms to listOfMyIntType Example <listOfMyInt>20003 15037 95977 95945</listOfMyInt> Several facets can be applied to list types: length minLength maxLength pattern enumeration SixUSStates USStateList USState SixUSStates USStateList Example List Type for Six US States <xsd:simpleType name="USStateList"> <xsd:list itemType="USState"/> </xsd:simpleType>
<xsd:simpleType name="SixUSStates"> <xsd:restriction base="USStateList"> <xsd:length value="6"/> </xsd:restriction> </xsd:simpleType> Elements whose type is SixUSStates USState Example <sixStates>PA NY CA NY LA AK</sixStates> Note that it is possible to derive a list type from the atomic type string string string length string Example Asie Europe Afrique But the following 3 "item" list is illegal: Example Asie Europe Amérique Latine Even though "Amérique Latine" may exist as a single string outside of the list, when it is included in the list, the whitespace between Amérique and Latine effectively creates a fourth item, and so the latter example will not conform to the 3-item list type. Atomic types and list types enable an element or an attribute value to be one or more instances of one atomic type. In contrast, a union type enables an element or attribute value to be one or more instances of one type drawn from the union of multiple atomic and list types. To illustrate, we create a union type for representing American states as singleton letter abbreviations or lists of numeric codes. The zipUnion Example Union Type for Zip Codes <xsd:simpleType name="zipUnion"> <xsd:union memberTypes="USState listOfMyIntType"/> </xsd:simpleType> When we define a union type, the memberTypes Now, assuming we have declared an element called zips zipUnion Example <zips>CA</zips> <zips>95630 95977 95945</zips> <zips>AK</zips> Two facets, pattern enumeration Schemas can be constructed by defining sets of named types such as PurchaseOrderType purchaseOrder type The definition of the type Items po.xsd item quantity type Example Two Anonymous Type Definitions <xsd:complexType name="Items"> <xsd:sequence> <xsd:element name="item" minOccurs="0" maxOccurs="unbounded"> <xsd:complexType> <xsd:sequence> <xsd:element name="productName" type="xsd:string"/> <xsd:element name="quantity"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="100"/> </xsd:restriction> </xsd:simpleType> </xsd:element> <xsd:element name="USPrice" type="xsd:decimal"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/> </xsd:sequence> <xsd:attribute name="partNum" type="SKU" use="required"/> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> In the case of the item productName quantity USPrice comment shipDate partNum quantity positiveInteger 2.5.1 Complex Types from Simple Types Mixed Content Empty Content anyType The purchase order schema has many examples of elements containing other elements (e.g. items shipTo USPrice Let us first consider how to declare an element that has an attribute and contains a simple value. In an instance document, such an element might appear as: Example <internationalPrice currency="EUR">423.46</internationalPrice> The purchase order schema declares a USPrice Example <xsd:element name="USPrice" type="decimal"/> Now, how do we add an attribute to this element? As we have said before, simple types cannot have attributes, and decimal decimal decimal derive decimal Example Deriving a Complex Type from a Simple Type <xsd:element name="internationalPrice"> <xsd:complexType> <xsd:simpleContent> <xsd:extension base="xsd:decimal"> <xsd:attribute name="currency" type="xsd:string"/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> We use the complexType simpleContent decimal currency Advanced Concepts II: The International Purchase Order (§4) internationalPrice The construction of the purchase order schema may be characterized as elements containing subelements, and the deepest subelements contain character data. XML Schema also provides for the construction of schemas where character data can appear alongside subelements, and character data is not confined to the deepest subelements. To illustrate, consider the following snippet from a customer letter that uses some of the same elements as the purchase order: Example Snippet of Customer Letter <letterBody> <salutation>Dear Mr.<name>Robert Smith</name>.</salutation> Your order of <quantity>1</quantity> <productName>Baby Monitor</productName> shipped from our warehouse on <shipDate>1999-05-21</shipDate>. .... </letterBody> Notice the text appearing between elements and their child elements. Specifically, text appears between the elements salutation quantity productName shipDate letterBody name letterBody letterBody Example Snippet of Schema for Customer Letter <xsd:element name="letterBody"> <xsd:complexType mixed="true"> <xsd:sequence> <xsd:element name="salutation"> <xsd:complexType mixed="true"> <xsd:sequence> <xsd:element name="name" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="quantity" type="xsd:positiveInteger"/> <xsd:element name="productName" type="xsd:string"/> <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/> <!-- etc. --> </xsd:sequence> </xsd:complexType> </xsd:element> The elements appearing in the customer letter are declared, and their types are defined using the element complexType letterBody mixed Note that the mixed mixed model in XML 1.0 Now suppose that we want the internationalPrice Example <internationalPrice currency="EUR" value="423.46"/> Such an element has no content at all; its content model is empty. To define a type whose content is empty, we essentially define a type that allows only elements in its content, but we do not actually declare any elements and so the type's content model is empty: Example An Empty Complex Type <xsd:element name="internationalPrice"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:attribute name="currency" type="xsd:string"/> <xsd:attribute name="value" type="xsd:decimal"/> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> In this example, we define an (anonymous) type having complexContent complexContent restriction anyType Deriving Complex Types by Restriction (§4.4) internationalPrice The preceding syntax for an empty-content element is relatively verbose, and it is possible to declare the internationalPrice Example Shorthand for an Empty Complex Type <xsd:element name="internationalPrice"> <xsd:complexType> <xsd:attribute name="currency" type="xsd:string"/> <xsd:attribute name="value" type="xsd:decimal"/> </xsd:complexType> </xsd:element> This compact syntax works because a complex type defined without any simpleContent complexContent anyType The anyType ur-type anyType anyType Example <xsd:element name="anything" type="xsd:anyType"/> The content of the element declared in this way is unconstrained, so the element value may be 423.46, but it may be any other sequence of characters as well, or indeed a mixture of characters and elements. In fact, anyType Example <xsd:element name="anything"/> If unconstrained element content is needed, for example in the case of elements containing prose which requires embedded markup to support internationalization, then the default declaration or a slightly restricted form of it may be suitable. The text Any Element, Any Attribute (§5.5) XML Schema provides three elements for annotating schemas for the benefit of both human readers and applications. In the purchase order schema, we put a basic schema description and copyright information inside the documentation xml:lang documentation xml:lang schema The appinfo appinfo schema appinfo Both documentation appinfo annotation annotation Example Annotations in Element Declaration & Complex Type Definition <xsd:element name="internationalPrice"> <xsd:annotation> <xsd:documentation xml:lang="en"> element declared with anonymous type </xsd:documentation> </xsd:annotation> <xsd:complexType> <xsd:annotation> <xsd:documentation xml:lang="en"> empty anonymous type with 2 attributes </xsd:documentation> </xsd:annotation> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:attribute name="currency" type="xsd:string"/> <xsd:attribute name="value" type="xsd:decimal"/> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> The annotation schema simpleType attribute The definitions of complex types in the purchase order schema all declare sequences of elements that must appear in the instance document. The occurrence of individual elements declared in the so-called content models of these types may be optional, as indicated by a 0 value for the attribute minOccurs comment minOccurs maxOccurs XML Schema enables groups of elements to be defined and named, so that the elements can be used to build up the content models of complex types (thus mimicking common usage of parameter entities in XML 1.0). Un-named groups of elements can also be defined, and along with elements in named groups, they can be constrained to appear in the same order (sequence) as they are declared. Alternatively, they can be constrained so that only one of the elements may appear in an instance. To illustrate, we introduce two groups into the PurchaseOrderType Example Nested Choice and Sequence Groups <xsd:complexType name="PurchaseOrderType"> <xsd:sequence> <xsd:choice> <xsd:group ref="shipAndBill"/> <xsd:element name="singleUSAddress" type="USAddress"/> </xsd:choice> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="items" type="Items"/> </xsd:sequence> <xsd:attribute name="orderDate" type="xsd:date"/> </xsd:complexType>
<xsd:group id="shipAndBill"> <xsd:sequence> <xsd:element name="shipTo" type="USAddress"/> <xsd:element name="billTo" type="USAddress"/> </xsd:sequence> </xsd:group> The choice group shipAndBill shipTo billTo singleUSAddress purchaseOrder shipTo billTo singleUSAddress choice comment items choice sequence comment items There exists a third option for constraining elements in a group: All the elements in the group may appear once or not at all, and they may appear in any order. The all minOccurs maxOccurs purchaseOrder PurchaseOrderType Example An 'All' Group <xsd:complexType name="PurchaseOrderType"> <xsd:all> <xsd:element name="shipTo" type="USAddress"/> <xsd:element name="billTo" type="USAddress"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="items" type="Items"/> </xsd:all> <xsd:attribute name="orderDate" type="xsd:date"/> </xsd:complexType> By this definition, a comment purchaseOrder shipTo billTo items all comment all Example Illegal Example with an 'All' Group <xsd:complexType name="PurchaseOrderType"> <xsd:sequence> <xsd:all> <xsd:element name="shipTo" type="USAddress"/> <xsd:element name="billTo" type="USAddress"/> <xsd:element name="items" type="Items"/> </xsd:all> <xsd:sequence> <xsd:element ref="comment" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence> </xsd:sequence> <xsd:attribute name="orderDate" type="xsd:date"/> </xsd:complexType> Finally, named and un-named groups that appear in content models (represented by group choice sequence all minOccurs maxOccurs minOccurs maxOccurs all Suppose we want to provide more information about each item in a purchase order, for example, each item's weight and preferred shipping method. We can accomplish this by adding weightKg shipBy item Example Adding Attributes to the Inline Type Definition <xsd:element name="item" minOccurs="0" maxOccurs="unbounded"> <xsd:complexType> <xsd:sequence> <xsd:element name="productName" type="xsd:string"/> <xsd:element name="quantity"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="100"/> </xsd:restriction> </xsd:simpleType> </xsd:element> <xsd:element name="USPrice" type="xsd:decimal"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/> </xsd:sequence> <xsd:attribute name="partNum" type="SKU" use="required"/> <!-- add weightKg and shipBy attributes --> <xsd:attribute name="weightKg" type="xsd:decimal"/> <xsd:attribute name="shipBy"> <xsd:simpleType> <xsd:restriction base="xsd:string"> <xsd:enumeration value="air"/> <xsd:enumeration value="land"/> <xsd:enumeration value="any"/> </xsd:restriction> </xsd:simpleType> </xsd:attribute> </xsd:complexType> </xsd:element> Alternatively, we can create a named attribute group containing all the desired attributes of an item item Example Adding Attributes Using an Attribute Group <xsd:element name="item" minOccurs="0" maxOccurs="unbounded"> <xsd:complexType> <xsd:sequence> <xsd:element name="productName" type="xsd:string"/> <xsd:element name="quantity"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="100"/> </xsd:restriction> </xsd:simpleType> </xsd:element> <xsd:element name="USPrice" type="xsd:decimal"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/> </xsd:sequence>
<!-- attributeGroup replaces individual declarations --> <xsd:attributeGroup ref="ItemDelivery"/> </xsd:complexType> </xsd:element>
<xsd:attributeGroup id="ItemDelivery"> <xsd:attribute name="partNum" type="SKU" use="required"/> <xsd:attribute name="weightKg" type="xsd:decimal"/> <xsd:attribute name="shipBy"> <xsd:simpleType> <xsd:restriction base="xsd:string"> <xsd:enumeration value="air"/> <xsd:enumeration value="land"/> <xsd:enumeration value="any"/> </xsd:restriction> </xsd:simpleType> </xsd:attribute> </xsd:attributeGroup> Using an attribute group in this way can improve the readability of schemas, and facilitates updating schemas because an attribute group can be defined and edited in one place and referenced in multiple definitions and declarations. These characteristics of attribute groups make them similar to parameter entities in XML 1.0. Note that an attribute group may contain other attribute groups. Note also that both attribute declarations and attribute group references must appear at the end of complex type definitions. One of the purchase order items listed in po.xml Lawnmower shipDate item item explicitly XML Schema's nil mechanism involves an "out of band" nil signal. In other words, there is no actual nil value that appears as element content, instead there is an attribute to indicate that the element content is nil. To illustrate, we modify the shipDate Example <xsd:element name="shipDate" type="xsd:date" nillable="true"/> And to explicitly represent that shipDate nil Example <shipDate xsi:nil="true"></shipDate> The nil http://www.w3.org/2001/XMLSchema-instance xsi: xsd: xsi: xsi:nil A schema can be viewed as a collection (vocabulary) of type definitions and element declarations whose names belong to a particular namespace called a target namespace. Target namespaces enable us to distinguish between definitions and declarations from different vocabularies. For example, target namespaces would enable us to distinguish between the declaration for element element http://www.w3.org/2001/XMLSchema When we want to check that an instance document conforms to one or more schemas (through a process called schema validation), we need to identify which element and attribute declarations and type definitions in the schemas should be used to check which elements and attributes in the instance document. The target namespace plays an important role in the identification process. We examine the role of the target namespace in the next section. The schema author also has several options that affect how the identities of elements and attributes are represented in instance documents. More specifically, the author can decide whether or not the appearance of locally declared elements and attributes in an instance must be qualified by a namespace, using either an explicit prefix or implicitly by default. The schema author's choice regarding qualification of local elements and attributes has a number of implications regarding the structures of schemas and instance documents, and we examine some of these implications in the following sections. In a new version of the purchase order schema, po1.xsd po1.xsd http://www.example.com/PO1 targetNamespace Qualification of local elements and attributes can be globally specified by a pair of attributes, elementFormDefault attributeFormDefault schema form unqualified qualified In po1.xsd elementFormDefault attributeFormDefault unqualified Example Purchase Order Schema with Target Namespace, po1.xsd <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:po="http://www.example.com/PO1" targetNamespace="http://www.example.com/PO1" elementFormDefault="unqualified" attributeFormDefault="unqualified">
<element name="purchaseOrder" type="po:PurchaseOrderType"/> <element name="comment" type="string"/>
<complexType name="PurchaseOrderType"> <sequence> <element name="shipTo" type="po:USAddress"/> <element name="billTo" type="po:USAddress"/> <element ref="po:comment" minOccurs="0"/> <!-- etc. --> </sequence> <!-- etc. --> </complexType>
<complexType name="USAddress"> <sequence> <element name="name" type="string"/> <element name="street" type="string"/> <!-- etc. --> </sequence> </complexType>
<!-- etc. -->
</schema> To see how the target namespace of this schema is populated, we examine in turn each of the type definitions and element declarations. Starting from the end of the schema, we first define a type called USAddress name street USAddress PurchaseOrderType shipTo billTo comment PurchaseOrderType po:USAddress po:USAddress po:comment http://www.example.com/PO1 USAddress comment At the beginning of the schema po1.xsd purchaseOrder comment purchaseOrder USAddress comment string po1.xsd string element complexType http://www.w3.org/2001/XMLSchema po1.xsd string element Let us now examine how the target namespace of the schema affects a conforming instance document: Example A Purchase Order with Unqualified Locals, po1.xml <?xml version="1.0"?> <apo:purchaseOrder xmlns:apo="http://www.example.com/PO1" orderDate="1999-10-20"> <shipTo country="US"> <name>Alice Smith</name> <street>123 Maple Street</street> <!-- etc. --> </shipTo> <billTo country="US"> <name>Robert Smith</name> <street>8 Oak Avenue</street> <!-- etc. --> </billTo> <apo:comment>Hurry, my lawn is going wild<!/apo:comment> <!-- etc. --> </apo:purchaseOrder> The instance document declares one namespace, http://www.example.com/PO1 apo: purchaseOrder comment po1.xsd purchaseOrder comment purchaseOrder comment The prefix apo: purchaseOrder comment elementFormDefault attributeFormDefault not shipTo billTo name street not purchaseOrder comment purchaseOrder schema po1.xsd shipTo complexType PurchaseOrderType When local elements and attributes are not required to be qualified, an instance author may require more or less knowledge about the details of the schema to create schema valid instance documents. More specifically, if the author can be sure that only the root element (such as purchaseOrder Global vs. Local Declarations (§3.3) Elements and attributes can be independently required to be qualified, although we start by describing the qualification of local elements. To specify that all locally declared elements in a schema must be qualified, we set the value of elementFormDefault qualified Example Modifications to po1.xsd <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:po="http://www.example.com/PO1" targetNamespace="http://www.example.com/PO1" elementFormDefault="qualified" attributeFormDefault="unqualified">
<element name="purchaseOrder" type="po:PurchaseOrderType"/> <element name="comment" type="string"/>
<complexType name="PurchaseOrderType"> <!-- etc. --> </complexType>
<!-- etc. -->
</schema> And in this conforming instance document, we qualify all the elements explicitly: Example A Purchase Order with Explicitly Qualified Locals <?xml version="1.0"?> <apo:purchaseOrder xmlns:apo="http://www.example.com/PO1" orderDate="1999-10-20"> <apo:shipTo country="US"> <apo:name>Alice Smith</apo:name> <apo:street>123 Maple Street</apo:street> <!-- etc. --> </apo:shipTo> <apo:billTo country="US"> <apo:name>Robert Smith</apo:name> <apo:street>8 Oak Avenue</apo:street> <!-- etc. --> </apo:billTo> <apo:comment>Hurry, my lawn is going wild<!/apo:comment> <!-- etc. --> </apo:purchaseOrder> Alternatively, we can replace the explicit qualification of every element with implicit qualification provided by a default namespace, as shown here in po2.xml Example A Purchase Order with Default Qualified Locals, po2.xml <?xml version="1.0"?> <purchaseOrder xmlns="http://www.example.com/PO1" orderDate="1999-10-20"> <shipTo country="US"> <name>Alice Smith</name> <street>123 Maple Street</street> <!-- etc. --> </shipTo> <billTo country="US"> <name>Robert Smith</name> <street>8 Oak Avenue</street> <!-- etc. --> </billTo> <comment>Hurry, my lawn is going wild<!/comment> <!-- etc. --> </purchaseOrder> In po2.xml Advanced Concepts III: The Quarterly Report (§5) Qualification of attributes is very similar to the qualification of elements. Attributes that must be qualified, either because they are declared globally or because the attributeFormDefault qualified xsi:nil Nil Values (§2.9) Namespaces in XML The qualification mechanism we have described so far has controlled all local element and attribute declarations within a particular target namespace. It is also possible to control qualification on a declaration by declaration basis using the form publicKey Example Requiring Qualification of Single Attribute <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:po="http://www.example.com/PO1" targetNamespace="http://www.example.com/PO1" elementFormDefault="qualified" attributeFormDefault="unqualified"> <!-- etc. --> <element name="secure"> <complexType> <sequence> <!-- element declarations --> </sequence> <attribute name="publicKey" type="base64Binary" form="qualified"/> </complexType> </element> </schema> Notice that the value of the form attributeFormDefault publicKey form Example Instance with a Qualified Attribute <?xml version="1.0"?> <purchaseOrder xmlns="http://www.example.com/PO1" xmlns:po="http://www.example.com/PO1" orderDate="1999-10-20"> <!-- etc. --> <secure po:publicKey="GpM7"> <!-- etc. --> </secure> </purchaseOrder> Another authoring style, applicable when all element names are unique within a namespace, is to create schemas in which all elements are global. This is similar in effect to the use of <!ELEMENT> in a DTD. In the example below, we have modified the original po1.xsd elementFormDefault attributeFormDefault Example Modified version of po1.xsd <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:po="http://www.example.com/PO1" targetNamespace="http://www.example.com/PO1">
<element name="purchaseOrder" type="po:PurchaseOrderType"/>
<element name="shipTo" type="po:USAddress"/> <element name="billTo" type="po:USAddress"/> <element name="comment" type="string"/>
<element name="name" type="string"/> <element name="street" type="string"/>
<complexType name="PurchaseOrderType"> <sequence> <element ref="po:shipTo"/> <element ref="po:billTo"/> <element ref="po:comment" minOccurs="0"/> <!-- etc. --> </sequence> </complexType>
<complexType name="USAddress"> <sequence> <element ref="po:name"/> <element ref="po:street"/> <!-- etc. --> </sequence> </complexType>
<!-- etc. -->
</schema> This "global" version of po1.xsd po2.xml po1.xsd In Basic Concepts: The Purchase Order (§2) In the purchase order schema, po.xsd po USAddress purchaseOrder purchaseOrder PurchaseOrderType po.xsd xsd: In cases where a schema is designed without a target namespace, it is strongly recommended that all XML Schema elements and types are explicitly xsd: po.xsd Element declarations from a schema with no target namespace validate unqualified elements in the instance document. That is, they validate elements for which no namespace qualification is provided by either an explicit prefix or by default ( xmlns: The purchase order schema described in Basic Concepts: The Purchase Order (§2) As schemas become larger, it is often desirable to divide their content among several schema documents for purposes such as ease of maintenance, access control, and readability. For these reasons, we have taken the schema constructs concerning addresses out of po.xsd address.xsd ipo.xsd Example The International Purchase Order Schema, ipo.xsd <schema targetNamespace="http://www.example.com/IPO" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ipo="http://www.example.com/IPO">
<annotation> <documentation xml:lang="en"> International Purchase order schema for Example.com Copyright 2000 Example.com. All rights reserved. </documentation> </annotation>
<!-- include address constructs --> <include schemaLocation="http://www.example.com/schemas/address.xsd"/>
<element name="purchaseOrder" type="ipo:PurchaseOrderType"/>
<element name="comment" type="string"/>
<complexType name="PurchaseOrderType"> <sequence> <element name="shipTo" type="ipo:Address"/> <element name="billTo" type="ipo:Address"/> <element ref="ipo:comment" minOccurs="0"/> <element name="items" type="ipo:Items"/> </sequence> <attribute name="orderDate" type="date"/> </complexType>
<complexType name="Items"> <sequence> <element name="item" minOccurs="0" maxOccurs="unbounded"> <complexType> <sequence> <element name="productName" type="string"/> <element name="quantity"> <simpleType> <restriction base="positiveInteger"> <maxExclusive value="100"/> </restriction> </simpleType> </element> <element name="USPrice" type="decimal"/> <element ref="ipo:comment" minOccurs="0"/> <element name="shipDate" type="date" minOccurs="0"/> </sequence> <attribute name="partNum" type="ipo:SKU" use="required"/> </complexType> </element> </sequence> </complexType>
<simpleType name="SKU"> <restriction base="string"> <pattern value="\d{3}-[A-Z]{2}"/> </restriction> </simpleType>
</schema> The file containing the address constructs is: Example Addresses for International Purchase Order schema, address.xsd <schema targetNamespace="http://www.example.com/IPO" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ipo="http://www.example.com/IPO">
<annotation> <documentation xml:lang="en"> Addresses for International Purchase order schema Copyright 2000 Example.com. All rights reserved. </documentation> </annotation>
<complexType name="Address"> <sequence> <element name="name" type="string"/> <element name="street" type="string"/> <element name="city" type="string"/> </sequence> </complexType>
<complexType name="USAddress"> <complexContent> <extension base="ipo:Address"> <sequence> <element name="state" type="ipo:USState"/> <element name="zip" type="positiveInteger"/> </sequence> </extension> </complexContent> </complexType>
<complexType name="UKAddress"> <complexContent> <extension base="ipo:Address"> <sequence> <element name="postcode" type="ipo:UKPostcode"/> </sequence> <attribute name="exportCode" type="positiveInteger" fixed="1"/> </extension> </complexContent> </complexType>
<!-- other Address derivations for more countries -->
<simpleType name="USState"> <restriction base="string"> <enumeration value="AK"/> <enumeration value="AL"/> <enumeration value="AR"/> <!-- and so on ... --> </restriction> </simpleType>
<!-- simple type definition for UKPostcode -->
</schema> The various purchase order and address constructions are now contained in two schema files, ipo.xsd address.xsd ipo.xsd include Example <include schemaLocation="http://www.example.com/schemas/address.xsd"/> The effect of this include address.xsd include http://www.example.com/IPO include Redefining Types & Groups (§4.5) In our example, we have shown only one including document and one included document. In practice it is possible to include more than one document using multiple include Instance documents that conform to schema whose definitions span multiple schema documents need only reference the 'topmost' document and the common namespace, and it is the responsibility of the processor to gather together all the definitions specified in the various included documents. In our example above, the instance document ipo.xml Using Derived Types in Instance Documents (§4.3) http://www.example.com/IPO http://www.example.com/schemas/ipo.xsd address.xsd In Importing Types (§5.4) To create our address constructs, we start by creating a complex type called Address address.xsd Address Complex Types from Simple Types (§2.5.1) We define the two new complex types, USAddress UKAddress complexType complexContent Address base extension When a complex type is derived by extension, its effective content model is the content model of the base type plus the content model specified in the type derivation. Furthermore, the two content models are treated as two children of a sequential group. In the case of UKAddress UKAddress Address postcode exportCode UKAddress Example Effective Content Model of UKAddress <complexType name="UKAddress"> <sequence> <!-- content model of Address --> <element name="name" type="string"/> <element name="street" type="string"/> <element name="city" type="string"/>
<!-- appended element declaration --> <element name="postcode" type="ipo:UKPostcode"/> </sequence>
<!-- appended attribute declaration --> <attribute name="exportCode" type="positiveInteger" fixed="1"/> </complexType> In our example scenario, purchase orders are generated in response to customer orders which may involve shipping and billing addresses in different countries. The international purchase order, ipo.xml Address XML Schema allows us to define the billTo shipTo Address ipo.xsd Address UKAddress Address UKAddress xsi:type ipo.xml UKAddress USAddress xsi:type Example An International Purchase order, ipo.xml <?xml version="1.0"?> <ipo:purchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ipo="http://www.example.com/IPO" orderDate="1999-12-01">
<shipTo exportCode="1" xsi:type="ipo:UKAddress"> <name>Helen Zoe</name> <street>47 Eden Street</street> <city>Cambridge</city> <postcode>CB1 1JR</postcode> </shipTo>
<billTo xsi:type="ipo:USAddress"> <name>Robert Smith</name> <street>8 Oak Avenue</street> <city>Old Town</city> <state>PA</state> <zip>95819</zip> </billTo>
<items> <item partNum="833-AA"> <productName>Lapis necklace</productName> <quantity>1</quantity> <USPrice>99.95</USPrice> <ipo:comment>Want this for the holidays<!/ipo:comment> <shipDate>1999-12-05</shipDate> </item> </items> </ipo:purchaseOrder> In Controlling the Creation & Use of Derived Types (§4.8) In addition to deriving new complex types by extending content models, it is possible to derive new types by restricting the content models of existing types. Restriction of complex types is conceptually the same as restriction of simple types, except that the restriction of complex types involves a type's declarations rather than the acceptable range of a simple type's values. A complex type derived by restriction is very similar to its base type, except that its declarations are more limited than the corresponding declarations in the base type. In fact, the values represented by the new type are a subset of the values represented by the base type (as is the case with restriction of simple types). In other words, an application prepared for the values of the base type would not be surprised by the values of the restricted type. For example, suppose we want to update our definition of a purchase order so that it must contain a comment ipo.xsd purchaseOrder comment RestrictedPurchaseOrderType PurchaseOrderType comment RestrictedPurchaseOrderType orderDate PurchaseOrderType Example Deriving RestrictedPurchaseOrderType by Restriction from PurchaseOrderType <complexType name="RestrictedPurchaseOrderType"> <complexContent> <restriction base="ipo:PurchaseOrderType"> <sequence> <element name="shipTo" type="ipo:Address"/> <element name="billTo" type="ipo:Address"/> <element ref="ipo:comment" minOccurs="1"/> <element name="items" type="ipo:Items"/> </sequence> </restriction> </complexContent> </complexType> This change narrows the allowable number of comment RestrictedPurchaseOrderType PurchaseOrderType To further illustrate restriction, Table 3 Table 3. Restriction Examples Base Restriction(s) Notes default="1" setting a default value where none was previously given fixed="100" setting a fixed value where none was previously given type=" string specifying a type where none was previously given ( minOccurs maxOccurs ( minOccurs maxOccurs (0, 1) (0, 0) exclusion of an optional component; this may also be accomplished by omitting the component's declaration from the restricted type definition (0, 1) (1, 1) making an optional component required (0, unbounded) (0, 0) (0, 37) (1, 37) (1, 9) (1, 8) (2, 9) (4, 7) (3, 3) (1, unbounded) (1, 12) (3, unbounded) (6, 6) (1, 1) (1, 1) cannot further restrict minOccurs maxOccurs In A Schema in Multiple Documents (§4.1) include redefine include redefine To illustrate the redefine include ipo.xsd Address address.xsd Example Using redefine in the International Purchase Order <schema targetNamespace="http://www.example.com/IPO" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ipo="http://www.example.com/IPO">
<!-- bring in address constructs --> <redefine schemaLocation="http://www.example.com/schemas/address.xsd">
<!-- redefinition of Address --> <complexType name="Address"> <complexContent> <extension base="ipo:Address"> <sequence> <element name="country" type="string"/> </sequence> </extension> </complexContent> </complexType>
</redefine>
<!-- etc. -->
</schema> The redefine include address.xsd Address country Address Address redefine Address Address Now that Address Address address.xsd Address Address Example Snippet of ipo.xml .... <shipTo exportCode="1" xsi:type="ipo:UKAddress"> <name>Helen Zoe</name> <street>47 Eden Street</street> <city>Cambridge</city> <!-- country was added to Address which is base type of UKAddress --> <country>United Kingdom</country> <!-- postcode was added as part of UKAddress --> <postcode>CB1 1JR</postcode> </shipTo> .... Our example has been carefully constructed so that the redefined Address Address Address country Address Address Address redefine XML Schema provides a mechanism, called substitution groups, that allows elements to be substituted for other elements. More specifically, elements can be assigned to a special group of elements that are said to be substitutable for a particular named element called the head element. (Note that the head element as well as the substitutable elementsmust be declared as global elements.) To illustrate, we declare two elements called customerComment shipComment comment customerComment shipComment comment comment Example Declaring Elements Substitutable for comment <element name="shipComment" type="string" substitutionGroup="ipo:comment"/> <element name="customerComment" type="string" substitutionGroup="ipo:comment"/> When these declarations are added to the international purchase order schema, shipComment customerComment comment Example Snippet of ipo.xml .... <items> <item partNum="833-AA"> <productName>Lapis necklace</productName> <quantity>1</quantity> <USPrice>99.95</USPrice> <ipo:shipComment> Use gold wrap if possible </ipo:shipComment> <ipo:customerComment> Want this for the holidays! </ipo:customerComment> <shipDate>1999-12-05</shipDate> </item> </items> .... Note that when an instance document contains element substitutions whose types are derived from those of their head elements, it is not xsi:type Using Derived Types in Instance Documents (§4.3) The existence of a substitution group does not require any of the elements in that class to be used, nor does it preclude use of the head element. It simply provides a mechanism for allowing elements to be used interchangeably. XML Schema provides a mechanism to force substitution for a particular element or type. When an element or type is declared to be "abstract", it cannot be used in an instance document. When an element is declared to be abstract, a member of that element's substitution group must appear in the instance document. When an element's corresponding type definition is declared as abstract, all instances of that element must use xsi:type In the substitution group example we described in Substitution Groups (§4.6) comment customerComment shipComment comment ipo.xsd Example <element name="comment" type="string" abstract="true"/> With comment customerComment shipComment Declaring an element as abstract requires the use of a substitution group. Declaring a type as abstract simply requires the use of a type derived from it (and identified by the xsi:type Example Schema for Vehicles <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://cars.example.com/schema" xmlns:target="http://cars.example.com/schema">
<complexType name="Vehicle" abstract="true"/>
<complexType name="Car"> <complexContent> <extension base="target:Vehicle"/> </complexContent> </complexType>
<complexType name="Plane"> <complexContent> <extension base="target:Vehicle"/> </complexContent> </complexType>
<element name="transport" type="target:Vehicle"/> </schema> The transport xsi:type Example <transport xmlns="http://cars.example.com/schema"/> because the transport Example <transport xmlns="http://cars.example.com/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Car"/> because it uses a non-abstract type that is substitutable for Vehicle So far, we have been able to derive new types and use them in instance documents without any restraints. In reality, schema authors will sometimes want to control derivations of particular types, and the use of derived types in instances. XML Schema provides a couple of mechanisms that control the derivation of types. One of these mechanisms allows the schema author to specify that for a particular complex type, new types may not be derived from it, either (a) by restriction, (b) by extension, or (c) at all. To illustrate, suppose we want to prevent any derivation of the Address USAddress UKAddress Address Example Preventing Derivations by Restriction of Address <complexType name="Address" final="restriction"> <sequence> <element name="name" type="string"/> <element name="street" type="string"/> <element name="city" type="string"/> </sequence> </complexType> The restriction final #all extension finalDefault schema final finalDefault final Another type-derivation mechanism controls which facets can be applied in the derivation of a new simple type. When a simple type is defined, the fixed Postcode Example Preventing Changes to Simple Type Facets <simpleType name="Postcode"> <restriction base="string"> <length value="7" fixed="true"/> </restriction> </simpleType> Once this simple type has been defined, we can derive a new postal code type in which we apply a facet not fixed in the base definition, for example: Example Legal Derivation from Postcode <simpleType name="UKPostcode"> <restriction base="ipo:Postcode"> <pattern value="[A-Z]{2}\d\s\d[A-Z]{2}"/> </restriction> </simpleType> However, we cannot derive a new postal code in which we re-apply any facet that was fixed in the base definition: Example Illegal Derivation from Postcode <simpleType name="UKPostcode"> <restriction base="ipo:Postcode"> <pattern value="[A-Z]{2}\d\d[A-Z]{2}"/> <!-- illegal attempt to modify facet fixed in base type --> <length value="6" fixed="true"/> </restriction> </simpleType> In addition to the mechanisms that control type derivations, XML Schema provides a mechanism that controls which derivations and substitution groups may be used in instance documents. In Using Derived Types in Instance Documents (§4.3) USAddress UKAddress shipTo billTo Address Address block Address Address final Address Example Preventing Derivations by Restriction of Address in the Instance <complexType name="Address" block="restriction"> <sequence> <element name="name" type="string"/> <element name="street" type="string"/> <element name="city" type="string"/> </sequence> </complexType> The restriction block Address UKAddress USAddress Address #all extension final blockDefault schema block blockDefault block The home-products ordering and billing application can generate ad-hoc reports that summarize how many of which types of products have been billed on a per region basis. An example of such a report, one that covers the fourth quarter of 1999, is shown in 4Q99.xml Notice that in this section we use qualified elements in the schema, and default namespaces where possible in the instances. Example Quarterly Report, 4Q99.xml <purchaseReport xmlns="http://www.example.com/Report" period="P3M" periodEnding="1999-12-31">
<regions> <zip code="95819"> <part number="872-AA" quantity="1"/> <part number="926-AA" quantity="1"/> <part number="833-AA" quantity="1"/> <part number="455-BX" quantity="1"/> </zip> <zip code="63143"> <part number="455-BX" quantity="4"/> </zip> </regions>
<parts> <part number="872-AA">Lawnmower</part> <part number="926-AA">Baby Monitor</part> <part number="833-AA">Lapis Necklace</part> <part number="455-BX">Sturdy Shelves</part> </parts>
</purchaseReport> The report lists, by number and quantity, the parts billed to various zip codes, and it provides a description of each part mentioned. In summarizing the billing data, the intention of the report is clear and the data is unambiguous because a number of constraints are in effect. For example, each zip code appears only once (uniqueness constraint). Similarly, the description of every billed part appears only once although parts may be billed to several zip codes (referential constraint), see for example part number 455-BX Example The Report Schema, report.xsd <schema targetNamespace="http://www.example.com/Report" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:r="http://www.example.com/Report" xmlns:xipo="http://www.example.com/IPO" elementFormDefault="qualified">
<!-- for SKU --> <import namespace="http://www.example.com/IPO"/>
<annotation> <documentation xml:lang="en"> Report schema for Example.com Copyright 2000 Example.com. All rights reserved. </documentation> </annotation>
<element name="purchaseReport"> <complexType> <sequence> <element name="regions" type="r:RegionsType"/> <element name="parts" type="r:PartsType"/> </sequence> <attribute name="period" type="duration"/> <attribute name="periodEnding" type="date"/> </complexType>
<unique name="dummy1"> <selector xpath="r:regions/r:zip"/> <field xpath="@code"/> </unique>
<key name="pNumKey"> <selector xpath="r:parts/r:part"/> <field xpath="@number"/> </key>
<keyref name="dummy2" refer="r:pNumKey"> <selector xpath="r:regions/r:zip/r:part"/> <field xpath="@number"/> </keyref>
</element>
<complexType name="RegionsType"> <sequence> <element name="zip" maxOccurs="unbounded"> <complexType> <sequence> <element name="part" maxOccurs="unbounded"> <complexType> <complexContent> <restriction base="anyType"> <attribute name="number" type="xipo:SKU"/> <attribute name="quantity" type="positiveInteger"/> </restriction> </complexContent> </complexType> </element> </sequence> <attribute name="code" type="positiveInteger"/> </complexType> </element> </sequence> </complexType>
<complexType name="PartsType"> <sequence> <element name="part" maxOccurs="unbounded"> <complexType> <simpleContent> <extension base="string"> <attribute name="number" type="xipo:SKU"/> </extension> </simpleContent> </complexType> </element> </sequence> </complexType>
</schema> XML Schema enables us to indicate that any attribute or element value must be unique within a certain scope. To indicate that one particular attribute or element value is unique, we use the unique report.xsd selector xpath r: regions/ r: zip zip field xpath @code code code xpath subset XML Path Language 1.0 We can also indicate combinations of fields that must be unique. Going back to our purchase order example, suppose we want each item to have a unique combination of part number and product name. We could achieve such a constraint by specifying that for each item partNum productName To define combinations of values, we simply use multiple field Example A Unique Composed Value <xsd:element name="items" type="Items"> <xsd:unique name="partNumAndName"> <xsd:selector xpath="item"/> <xsd:field xpath="@partNum"/> <xsd:field xpath="productName"/> </xsd:unique> </xsd:element> In the 1999 quarterly report, the description of every billed part appears only once. We could enforce this constraint using unique key keyref report.xsd key keyref unique number part parts number pNumKey To ensure that the part-quantity elements have corresponding part descriptions, we say that the number <field xpath="@number"/> <selector xpath="r:regions/r:zip/r:part"/> pNumKey number keyref pNumKey As you may have figured out by analogy with unique key keyref string integer date field key keyref XML 1.0 ID IDREF IDREFS attribute key keyref The report schema, report.xsd xipo:SKU include ipo.xsd address.xsd include include schemaLocation To import the type SKU SKU import SKU http://www.example.com/IPO xipo SKU http://www.example.com/IPO xipo:SKU In our example, we imported one simple type from one external namespace, and used it for declaring attributes. XML Schema in fact permits multiple schema components to be imported, from multiple namespaces, and they can be referred to in both definitions and declarations. For example in report.xsd comment ipo.xsd Example <element ref="xipo:comment"/> Note however, that we cannot reuse the shipTo ipo.xsd global Example <element ref="xipo:shipTo"/> In ipo.xsd comment schema shipTo PurchaseOrderType Complex types can also be imported, and they can be used as the base types for deriving new types. Only named complex types can be imported; local, anonymously defined types cannot. Suppose we want to include in our reports the name of an analyst, along with contact information. We can reuse the (globally defined) complex type USAddress address.xsd Analyst phone email Example Defining Analyst by Extending USAddress <complexType name="Analyst"> <complexContent> <extension base="xipo:USAddress"> <sequence> <element name="phone" type="string"/> <element name="email" type="string"/> </sequence> </extension> </complexContent> </complexType> Using this new type we declare an element called analyst purchaseReport Example Instance Document Conforming to Report Schema with Analyst Type <r:purchaseReport xmlns:r="http://www.example.com/Report" period="P3M" periodEnding="1999-12-31"> <!-- regions and parts elements omitted --> <r:analyst> <name>Wendy Uhro</name> <street>10 Corporate Towers</street> <city>San Jose</city> <state>CA</state> <zip>95113</zip> <r:phone>408-271-3366</r:phone> <r:email>[email protected]</r:email> </r:analyst> </r:purchaseReport> Note that the report now has both qualified and unqualified elements. This is because some of the elements ( name street city state zip ipo.xsd elementFormDefault unqualified report.xsd elementFormDefault qualified When schema components are imported from multiple namespaces, each namespace must be identified with a separate import import schema import schemaLocation schemaLocation As XML schemas become more widespread, schema authors will want to create simple and complex types that can be shared and used as building blocks for creating new schemas. XML Schemas already provides types that play this role, in particular, the types described in the Simple Types appendix type library Schema authors will undoubtedly want to create their own libraries of types to represent currency, units of measurement, business addresses, and so on. Each library might consist of a schema containing one or more definitions, for example, a schema containing a currency type: Example Example Currency Type in Type Library <schema targetNamespace="http://www.example.com/Currency" xmlns:c="http://www.example.com/Currency" xmlns="http://www.w3.org/2001/XMLSchema">
<annotation> <documentation xml:lang="en"> Definition of Currency type based on ISO 4217 </documentation> </annotation>
<complexType name="Currency"> <simpleContent> <extension base="decimal"> <attribute name="name"> <simpleType> <restriction base="string">
<enumeration value="AED"> <annotation> <documentation xml:lang="en"> United Arab Emirates: Dirham (1 Dirham = 100 Fils) </documentation> </annotation> </enumeration>
<enumeration value="AFA"> <annotation> <documentation xml:lang="en"> Afghanistan: Afghani (1 Afghani = 100 Puls) </documentation> </annotation> </enumeration>
<enumeration value="ALL"> <annotation> <documentation xml:lang="en"> Albania, Lek (1 Lek = 100 Qindarka) </documentation> </annotation> </enumeration>
<!-- and other currencies -->
</restriction> </simpleType> </attribute> </extension> </simpleContent> </complexType>
</schema> An example of an element appearing in an instance and having this type: Example <convertFrom name="AFA">199.37</convertFrom> Once we have defined the currency type, we can make it available for re-use in other schemas through the import In previous sections we have seen several mechanisms for extending the content models of complex types. For example, a mixed content model can contain arbitrary character data in addition to elements, and for example, a content model can contain elements whose types are imported from external namespaces. However, these mechanisms provide very broad and very narrow controls respectively. The purpose of this section is to describe a flexible mechanism that enables content models to be extended by any elements and attributes belonging to specified namespaces. To illustrate, consider a version of the quarterly report, 4Q99html.xml htmlExample table http://www.w3.org/1999/xhtml Example Quarterly Report with XHTML, 4Q99html.xml <purchaseReport xmlns="http://www.example.com/Report" period="P3M" periodEnding="1999-12-31">
<regions> <!-- part sales listed by zip code, data from 4Q99.xml --> </regions>
<parts> <!-- part descriptions from 4Q99.xml --> </parts>
<htmlExample> <table xmlns="http://www.w3.org/1999/xhtml" border="0" width="100%"> <tr> <th align="left">Zip Code</th> <th align="left">Part Number</th> <th align="left">Quantity</th> </tr> <tr><td>95819</td><td> </td><td> </td></tr> <tr><td> </td><td>872-AA</td><td>1</td></tr> <tr><td> </td><td>926-AA</td><td>1</td></tr> <tr><td> </td><td>833-AA</td><td>1</td></tr> <tr><td> </td><td>455-BX</td><td>1</td></tr> <tr><td>63143</td><td> </td><td> </td></tr> <tr><td> </td><td>455-BX</td><td>4</td></tr> </table> </htmlExample>
</purchaseReport> To permit the appearance of XHTML in the instance document we modify the report schema by declaring a new element htmlExample any any http://www.w3.org/1999/xhtml minOccurs maxOccurs Example Modification to purchaseReport Declaration to Allow XHTML in Instance <element name="purchaseReport"> <complexType> <sequence> <element name="regions" type="r:RegionsType"/> <element name="parts" type="r:PartsType"/> <element name="htmlExample"> <complexType> <sequence> <any namespace="http://www.w3.org/1999/xhtml" minOccurs="1" maxOccurs="unbounded" processContents="skip"/> </sequence> </complexType> </element> </sequence> <attribute name="period" type="duration"/> <attribute name="periodEnding" type="date"/> </complexType> </element> The modification permits some well-formed XML belonging to the namespace http://www.w3.org/1999/xhtml htmlExample 4Q99html.xml htmlExample 4Q99html.xml processContents strict htmlExample In another example, we define a text type library Type Libraries (§5.4.1) Ruby xml:lang lax processContents Example Text Type <xsd:complexType name="text"> <xsd:complexContent mixed="true"> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence> <xsd:attribute ref="xml:lang"/> </xsd:restriction> </xsd:complexContent> </xsd:complexType> Namespaces may be used to permit and forbid element content in various ways depending upon the value of the namespace Table 4 Table 4. Namespace Attribute in Any Value of Namespace Attribute Allowable Element Content ##any Any well-formed XML from any namespace (default) ##local Any well-formed XML that is not qualified, i.e. not declared to be in a namespace ##other Any well-formed XML that is from a namespace other than the target namespace of the type being defined (unqualified elements are not allowed) "http://www.w3.org/1999/xhtml ##targetNamespace" Any well-formed XML belonging to any namespace in the (whitespace separated) list; ##targetNamespace is shorthand for the target namespace of the type being defined In addition to the any anyAttribute htmlExample anyAttribute Example Modification to htmlExample Declaration to Allow XHTML Attributes <element name="htmlExample"> <complexType> <sequence> <any namespace="http://www.w3.org/1999/xhtml" minOccurs="1" maxOccurs="unbounded" processContents="skip"/> </sequence> <anyAttribute namespace="http://www.w3.org/1999/xhtml"/> </complexType> </element> This declaration permits an XHTML attribute, say href htmlExample Example An XHTML attribute in the htmlExample Element .... <htmlExample xmlns:h="http://www.w3.org/1999/xhtml" h:href="http://www.example.com/reports/4Q99.html"> <!-- XHTML markup here --> </htmlExample> .... The namespace anyAttribute Table 4 any anyAttribute processContents any anyAttribute XML Schema uses the schemaLocation xsi:schemaLocation 1. In an instance document, the attribute xsi:schemaLocation Example Using schemaLocation in the Quarterly Report, 4Q99html.xml <purchaseReport xmlns="http://www.example.com/Report" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/Report http://www.example.com/Report.xsd" period="P3M" periodEnding="1999-12-31">
<!-- etc. -->
</purchaseReport> The schemaLocation A schema is not required to have a namespace (see Undeclared Target Namespaces (§3.4) noNamespaceSchemaLocation 2. In a schema, the include schemaLocation Advanced Concepts II: The International Purchase Order (§4) Address USAddress UKAddress USState address.xsd purchaseOrder comment PurchaseOrderType Items SKU ipo.xsd 3. Also in a schema, the import namespace schemaLocation schemaLocation xsi:schemaLocation namespace import namespace schemaLocation Note that the schemaLocation An instance document may be processed against a schema to verify whether the rules specified in the schema are honored in the instance. Typically, such processing actually does two things, (1) it checks for conformance to the rules, a process called schema validation, and (2) it adds supplementary information that is not immediately present in the instance, such as types and default values, called infoset contributions. The author of an instance document, such as a particular purchase order, may claim, in the instance itself, that it conforms to the rules in a particular schema. The author does this using the schemaLocation schemaLocation schemaLocation Conformance checking can be thought of as proceeding in steps, first checking that the root element of the document instance has the right contents, then checking that each subelement conforms to its description in a schema, and so on until the entire document is verified. Processors are required to report what checking has been carried out. To check an element for conformance, the processor first locates the declaration for the element in a schema, and then checks that the targetNamespace targetNamespace Supposing the namespaces match, the processor then examines the type of the element, either as given by the declaration in the schema, or by an xsi:type block Next the processor checks the immediate attributes and contents of the element, comparing these against the attributes and contents permitted by the element's type. For example, considering a shipTo The Purchase Order Schema (§2.1) Address shipTo If the element has a simple type, the processor verifies that the element has no attributes or contained elements, and that its character content matches the rules for the simple type. This sometimes involves checking the character sequence against regular expressions or enumerations, and sometimes it involves checking that the character sequence represents a value in a permitted range. If the element has a complex type, then the processor checks that any required attributes are present and that their values conform to the requirements of their simple types. It also checks that all required subelements are present, and that the sequence of subelements (and any mixed text) matches the content model declared for the complex type. Regarding subelements, schemas can either require exact name matching, permit substitution by an equivalent element or permit substitution by any element allowed by an 'any' particle. Unless a schema indicates otherwise (as it can for 'any' particles) conformance checking then proceeds one level more deeply by looking at each subelement in turn, repeating the process described above. Many people have contributed ideas, material and feedback that has improved this document. In particular, the editor acknowledges contributions from David Beech, Paul Biron, Don Box, Allen Brown, David Cleary, Dan Connolly, Roger Costello, Martin Dürst, Martin Gudgin, Dave Hollander, Joe Kesselman, John McCarthy, Andrew Layman, Eve Maler, Ashok Malhotra, Noah Mendelsohn, Michael Sperberg-McQueen, Henry Thompson, Misha Wolf, and Priscilla Walmsley for validating the examples. At the time the first edition of this specification was published, the members of the XML Schema Working Group were: Jim Barnette, Defense Information Systems Agency (DISA) Paul V. Biron, Health Level Seven Don Box, DevelopMentor Allen Brown, Microsoft Lee Buck, TIBCO Extensibility Charles E. Campbell, Informix Wayne Carr, Intel Peter Chen, Bootstrap Alliance and LSU David Cleary, Progress Software Dan Connolly, W3C ( staff contact Ugo Corda, Xerox Roger L. Costello, MITRE Haavard Danielson, Progress Software Josef Dietl, Mozquito Technologies David Ezell, Hewlett-Packard Company Alexander Falk, Altova GmbH David Fallside, IBM Dan Fox, Defense Logistics Information Service (DLIS) Matthew Fuchs, Commerce One Andrew Goodchild, Distributed Systems Technology Centre (DSTC Pty Ltd) Paul Grosso, Arbortext, Inc Martin Gudgin, DevelopMentor Dave Hollander, Contivo, Inc ( co-chair Mary Holstege, Invited Expert Jane Hunter, Distributed Systems Technology Centre (DSTC Pty Ltd) Rick Jelliffe, Academia Sinica Simon Johnston, Rational Software Bob Lojek, Mozquito Technologies Ashok Malhotra, Microsoft Lisa Martin, IBM Noah Mendelsohn, Lotus Development Corporation Adrian Michel, Commerce One Alex Milowski, Invited Expert Don Mullen, TIBCO Extensibility Dave Peterson, Graphic Communications Association Jonathan Robie, Software AG Eric Sedlar, Oracle Corp. C. M. Sperberg-McQueen, W3C ( co-chair Bob Streich, Calico Commerce William K. Stumbo, Xerox Henry S. Thompson, University of Edinburgh Mark Tucker, Health Level Seven Asir S. Vedamuthu, webMethods, Inc Priscilla Walmsley, XMLSolutions Norm Walsh, Sun Microsystems Aki Yoshida, SAP AG Kongyi Zhou, Oracle Corp. The XML Schema Working Group has benefited in its work from the participation and contributions of a number of people not currently members of the Working Group, including in particular those named below. Affiliations given are those current at the time of their work with the WG. Paula Angerstein, Vignette Corporation David Beech, Oracle Corp. Gabe Beged-Dov, Rogue Wave Software Greg Bumgardner, Rogue Wave Software Dean Burson, Lotus Development Corporation Mike Cokus, MITRE Andrew Eisenberg, Progress Software Rob Ellman, Calico Commerce George Feinberg, Object Design Charles Frankston, Microsoft Ernesto Guerrieri, Inso Michael Hyman, Microsoft Renato Iannella, Distributed Systems Technology Centre (DSTC Pty Ltd) Dianne Kennedy, Graphic Communications Association Janet Koenig, Sun Microsystems Setrag Khoshafian, Technology Deployment International (TDI) Ara Kullukian, Technology Deployment International (TDI) Andrew Layman, Microsoft Dmitry Lenkov, Hewlett-Packard Company John McCarthy, Lawrence Berkeley National Laboratory Murata Makoto, Xerox Eve Maler, Sun Microsystems Murray Maloney, Muzmo Communication, acting for Commerce One Chris Olds, Wall Data Frank Olken, Lawrence Berkeley National Laboratory Shriram Revankar, Xerox Mark Reinhold, Sun Microsystems John C. Schneider, MITRE Lew Shannon, NCR William Shea, Merrill Lynch Ralph Swick, W3C Tony Stewart, Rivcom Matt Timmermans, Microstar Jim Trezzo, Oracle Corp. Steph Tryphonas, Microstar The lists given above pertain to the first edition. At the time work on this second edition was completed, the membership of the Working Group was: Leonid Arbouzov, Sun Microsystems Jim Barnette, Defense Information Systems Agency (DISA) Paul V. Biron, Health Level Seven Allen Brown, Microsoft Charles E. Campbell, Invited expert Peter Chen, Invited expert Tony Cincotta, NIST David Ezell, National Association of Convenience Stores Matthew Fuchs, Invited expert Sandy Gao, IBM Andrew Goodchild, Distributed Systems Technology Centre (DSTC Pty Ltd) Xan Gregg, Invited expert Mary Holstege, Mark Logic Mario Jeckle, DaimlerChrysler Marcel Jemio, Data Interchange Standards Association Kohsuke Kawaguchi, Sun Microsystems Ashok Malhotra, Invited expert Lisa Martin, IBM Jim Melton, Oracle Corp Noah Mendelsohn, IBM Dave Peterson, Invited expert Anli Shundi, TIBCO Extensibility C. M. Sperberg-McQueen, W3C ( co-chair Hoylen Sue, Distributed Systems Technology Centre (DSTC Pty Ltd) Henry S. Thompson, University of Edinburgh Asir S. Vedamuthu, webMethods, Inc Priscilla Walmsley, Invited expert Kongyi Zhou, Oracle Corp. We note with sadness the accidental death of Mario Jeckle shortly after the completion of work on this document. In addition to those named above, several people served on the Working Group during the development of this second edition: Oriol Carbo, University of Edinburgh Tyng-Ruey Chuang, Academia Sinica Joey Coyle, Health Level 7 Tim Ewald, DevelopMentor Nelson Hung, Corel Melanie Kudela, Uniform Code Council Matthew MacKenzie, XML Global Cliff Schmidt, Microsoft John Stanton, Defense Information Systems Agency John Tebbutt, NIST Ross Thompson, Contivo Scott Vorthmann, TIBCO Extensibility The legal values for each simple type can be constrained through the application of one or more facets. Tables B1.a B1.b XML Schema Part 2: Datatypes Table B1.a. Simple Types & Applicable Facets Simple Types Facets length minLength maxLength pattern enumeration whiteSpace string y y y y y y normalizedString y y y y y y token y y y y y see (1) base64Binary y y y y y see (1) hexBinary y y y y y see (1) integer y y see (1) positiveInteger y y see (1) negativeInteger y y see (1) nonNegativeInteger y y see (1) nonPositiveInteger y y see (1) long y y see (1) unsignedLong y y see (1) int y y see (1) unsignedInt y y see (1) short y y see (1) unsignedShort y y see (1) byte y y see (1) unsignedByte y y see (1) decimal y y see (1) float y y see (1) double y y see (1) boolean y see (1) duration y y see (1) dateTime y y see (1) date y y see (1) time y y see (1) gYear y y see (1) gYearMonth y y see (1) gMonth y y see (1) gMonthDay y y see (1) gDay y y see (1) Name y y y y y see (1) QName y y y y y see (1) NCName y y y y y see (1) anyURI y y y y y see (1) language y y y y y see (1) ID y y y y y see (1) IDREF y y y y y see (1) IDREFS y y y y y see (1) ENTITY y y y y y see (1) ENTITIES y y y y y see (1) NOTATION y y y y y see (1) NMTOKEN y y y y y see (1) NMTOKENS y y y y y see (1) Note: (1) Although the whiteSpace collapse The facets listed in Table B1.b apply only to simple types which are ordered. Not all simple types are ordered and so B1.b does not list all of the simple types. Table B1.b. Simple Types & Applicable Facets Simple Types Facets max Inclusive max Exclusive min Inclusive min Exclusive total Digits fraction Digits integer y y y y y see (1) positiveInteger y y y y y see (1) negativeInteger y y y y y see (1) nonNegativeInteger y y y y y see (1) nonPositiveInteger y y y y y see (1) long y y y y y see (1) unsignedLong y y y y y see (1) int y y y y y see (1) unsignedInt y y y y y see (1) short y y y y y see (1) unsignedShort y y y y y see (1) byte y y y y y see (1) unsignedByte y y y y y see (1) decimal y y y y y y float y y y y double y y y y duration y y y y dateTime y y y y date y y y y time y y y y gYear y y y y gYearMonth y y y y gMonth y y y y gMonthDay y y y y gDay y y y y Note: (1) Although the fractionDigits XML 1.0 provides various types of entities which are named fragments of content that can be used in the construction of both DTD's (parameter entities) and instance documents. In Building Content Models (§2.7) Suppose we want to declare and use an entity in an instance document, and that document is also constrained by a schema. For example: Example Declaring and referencing an entity in an instance document. <?xml version="1.0" ?> <!DOCTYPE purchaseOrder [ <!ENTITY eacute "é"> ]> <purchaseOrder xmlns="http://www.example.com/PO1" orderDate="1999-10-20"> <!-- etc. --> <city>Montréal</city> <!-- etc. --> </purchaseOrder> Here, we declare an entity called eacute city city Montréal We can achieve a similar but not identical outcome by declaring an element in a schema, and by setting the element's content appropriately: Example <xsd:element name="eacute" type="xsd:token" fixed="é"/> And this element can be used in an instance document: Example Using an element instead of an entity in an instance document. <?xml version="1.0" ?> <purchaseOrder xmlns="http://www.example.com/PO1" xmlns:c="http://www.example.com/characterElements" orderDate="1999-10-20"> <!-- etc. --> <city>Montr<c:eacute/>al</city> <!-- etc. --> </purchaseOrder> In this case, a schema processor will process two elements, a city eacute é XML Schema's pattern Unicode XML Schema Part 2 Perl Programming language Table D1. Examples of Regular Expressions Expression Match(es) Chapter \d Chapter 0, Chapter 1, Chapter 2 .... Chapter\s\d Chapter followed by a single whitespace character (space, tab, newline, etc.), followed by a single digit Chapter\s\w Chapter followed by a single whitespace character (space, tab, newline, etc.), followed by a word character ( XML 1.0 Letter or Digit Española Española \p{Lu} any uppercase character, the value of \p{} (e.g. "Lu") is defined by Unicode \p{IsGreek} any Greek character, the 'Is' construction may be applied to any block name (e.g. "Greek") as defined by Unicode \P{IsGreek} any non-Greek character, the 'Is' construction may be applied to any block name (e.g. "Greek") as defined by Unicode a*x x, ax, aax, aaax .... a?x ax, x a+x ax, aax, aaax .... (a|b)+x ax, bx, aax, abx, bax, bbx, aaax, aabx, abax, abbx, baax, babx, bbax, bbbx, aaaax .... [abcde]x ax, bx, cx, dx, ex [a-e]x ax, bx, cx, dx, ex [\-ae]x -x, ax, ex [ae\-]x ax, ex, -x [^0-9]x any non-digit character followed by the character x \Dx any non-digit character followed by the character x .x any character followed by the character x .*abc.* 1x2abc, abc1x2, z3456abchooray .... ab{2}x abbx ab{2,4}x abbx, abbbx, abbbbx ab{2,}x abbx, abbbx, abbbbx .... (ab){2}x ababx Each element name is followed by one or more links to examples (identified by section number) in the Primer , plus a link to a formal XML description in either the Structures or Datatypes parts of the XML Schema specification. all (§2.7) Structures annotation (§2.6) Structures any (§5.5) Structures anyAttribute (§5.5) Structures appinfo (§2.6) Structures attribute (§2.2) Structures attributeGroup (§2.8) Structures choice (§2.7) Structures complexContent (§2.5.3) Structures complexType (§2.2) Structures documentation (§2.6) Structures element (§2.2) Structures enumeration (§2.3) Datatypes extension (§2.5.1) Structures (§4.2) Structures field (§5.1) Structures group (§2.7) Structures import (§5.4) Structures include (§4.1) Structures key (§5.2) Structures keyref (§5.2) Structures length (§2.3.1) Datatypes list (§2.3.1) Datatypes maxInclusive (§2.3) Datatypes maxLength (§2.3.1) Datatypes minInclusive (§2.3) Datatypes minLength (§2.3.1) Datatypes pattern (§2.3) Datatypes redefine (§4.5) Structures restriction (§2.3) Datatypes (§4.4) Structures schema (§2.1) Structures selector (§5.1) Structures sequence (§2.7) Structures simpleContent (§2.5.1) Structures simpleType (§2.3) Datatypes union (§2.3.2) Datatypes unique (§5.1) Structures Each attribute name is followed by one or more pairs of references. Each pair of references consists of a link to an example in the Primer, plus a link to a formal XML description in either the Structures or Datatypes parts of the XML Schema specification. abstract element declaration Structures abstract complex type definition Structures attributeFormDefault schema definition Structures base simple type definition Datatypes base complex type definition Structures block complex type definition Structures blockDefault schema definition Structures default attribute declaration Structures default element declaration Structures elementFormDefault schema definition Structures final complex type definition Structures finalDefault schema definition Structures fixed attribute declaration Structures fixed element declaration Structures fixed simple type definition Datatypes form attribute declaration Structures form element declaration Structures itemType list type definition Datatypes memberTypes union type definition Datatypes maxOccurs element declaration Structures minOccurs element declaration Structures mixed complex type definition Structures name element declaration Structures name attribute declaration Structures name complex type definition Structures name simple type definition Datatypes namespace element wildcard Structures namespace import specification Structures xsi:noNamespaceSchemaLocation instance element Structures xsi:nil instance element Structures nillable element declaration Structures processContents element wildcard Structures processContents attribute wildcard Structures ref element declaration Structures schemaLocation include specification Structures schemaLocation redefine specification Structures schemaLocation import specification Structures xsi:schemaLocation instance element Structures substitutionGroup element declaration Structures targetNamespace schema definition Structures type element declaration Structures type attribute declaration Structures xsi:type instance element Structures use attribute declaration Structures xpath identity constraint definition Structures XML Schema's simple types are described in Table 2