XML schema
An XML schema is a mechanism, defined by the W3C, for describing and constraining the structure and content of XML documents.
Through its support for datatypes and namespaces, an XML schema has the potential to provide the standard structure for XML elements and attributes. Therefore, an XML schema, which is itself expressed in XML, can effectively define a class of XML documents of a given type, for example, stock item.
The following sample XML document describes an item for stock keeping purposes:
'<?xml version="1.0" standalone="yes"?>'
|| '<!--Document for stock keeping example-->'
|| '<stockItem itemNumber="453-SR">'
|| '<itemName>Stainless steel rope thimbles</itemName>'
|| '<quantityOnHand>23</quantityOnHand>'
|| '<stockItem>';
The stock keeping example document is both well formed and valid
according to the following schema called stock.xsd.
(The numbers that precede each line are not part of the schema, but
are used in the explanation after the schema.)
1. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
2.
3. <xsd:element name="stockItem" type="stockItemType"/>
4.
5. <xsd:complexType name="stockItemType">
6. <xsd:sequence>
7. <xsd:element name="itemName" type="xsd:string" minOccurs="0"/>
8. <xsd:element name="quantityOnHand">
9. <xsd:simpleType>
10. <xsd:restriction base="xsd:nonNegativeInteger">
11. <xsd:maxExclusive value="100"/>
12. </xsd:restriction>
13. </xsd:simpleType>
14. </xsd:element>
15. </xsd:sequence>
16. <xsd:attribute name="itemNumber" type="SKU" use="required"/>
17. </xsd:complexType>
18.
19. <xsd:simpleType name="SKU">
20. <xsd:restriction base="xsd:string">
21. <xsd:pattern value="\d{3}-[A-Z]{2}"/>
22. </xsd:restriction>
23. </xsd:simpleType>
24.
25. </xsd:schema>
stockItem,
which has a mandatory itemNumber attribute (line
16) of type SKU, and includes a sequence (lines 6
- 15) of other elements: - An optional
itemNameelement of type string (line 7) - A required
quantityOnHandelement that has a constrained range of 1 - 99 based on the typenonNegativeInteger(lines 8 - 14)
Type declarations can be inline and unnamed, as in lines 9 - 13,
which includes the maxExclusive facet to specify
the legal values for the quantityOnHand element.
For the itemNumber attribute, by contrast, the
named type SKU is declared separately in lines 19
- 23, which includes a pattern facet that uses regular expression
syntax to specify that the legal values for that type consist of (in
order) 3 digits, a hyphen-minus, and then two uppercase letters.