Extensible Markup Language XML Tutorial

Quick syntax tour

The basic syntax for one element in XML is

<name attribute="value">content</name>

Here is an example of a simple recipe expressed using XML:

<?xml version="1.0" encoding="UTF-8"?>
<recipe name="bread" prep_time="5 mins" cook_time="3 hours">
<title>Basic bread</title>
<ingredient amount="3" unit="cups">Flour</ingredient>
<ingredient amount="0.25" unit="ounce">Yeast</ingredient>
<ingredient amount="1.5" unit="cups" state="warm">Water</ingredient>
<ingredient amount="1" unit="teaspoon">Salt</ingredient>
<instructions>
<step>Mix all ingredients together, and knead thoroughly.</step>
<step>Cover with a cloth, and leave for one hour in warm room.</step>
<step>Knead again, place in a tin, and then bake in the oven.</step>
</instructions>
</recipe>

XML declaration

The first line is the XML declaration: it is an optional line stating what version of XML is in use (normally version 1.0), and may also contain information about character encoding and external dependencies.

Elements

The remainder of this document consists of nested elements, some of which have attributes and content. An element typically consists of two tags, a start tag and an end tag, possibly surrounding text and other elements. The start tag consists of a name surrounded by angle brackets, like "<step>"; the end tag consists of the same name surrounded by angle brackets, but with a slash preceding the name, like "</step>". The element's content is everything that appears between the start tag and the end tag, including text and other (child) elements. The following is a complete XML element, with start tag, text content, and end tag:

<step>Knead again, place in a tin, and then bake in the oven.</step>

Attributes

In addition to text content, an element can contain attributes — name-value pairs included in the start tag after the element name. Attribute values must always be quoted, using single or double quotes, and each attribute name should appear only once in any element.

<ingredient amount="3" unit="cups">Flour</ingredient>

In this example, the ingredient element has two attributes: amount, having value "3", and unit, having value "cups". In both cases, at the markup level, the names and values of the attributes, just like the names and content of the elements, are just textual data — the "3" and "cups" are not a quantity and unit of measure, respectively, but rather are just character sequences that the document author may be using to represent those things.

Nesting

Elements may contain other elements:

<instructions>
<step>Mix all ingredients together, and knead thoroughly.</step>
<step>Cover with a cloth, and leave for one hour in warm room.</step>
<step>Knead again, place in a tin, and then bake in the oven.</step>
</instructions>

In this case, the instructions element contains three step elements. XML requires that elements be properly nested — elements may never overlap. For example, the code below is not well-formed XML, because the em and strong elements overlap:

<!-- WRONG! NOT WELL-FORMED XML! -->
<p>Normal <em>emphasized <strong>strong emphasized</em> strong</strong></p>

Document element

Every XML document must have exactly one top-level root element (alternatively called the document element), so the following would also be a malformed XML document: it has two top-level thing elements, with no overall parent element encasing them both.

<?xml version="1.0" encoding="UTF-8"?>
<!-- WRONG! NOT WELL-FORMED XML! -->
<thing>Thing one</thing>
<thing>Thing two</thing>

Empty elements

XML provides special syntax for representing an element with empty content. Instead of writing a start tag followed immediately by an end tag, a document may contain an empty or singleton tag. An empty tag is a start tag with a slash in front of the closing angle bracket. The following three examples are equivalent in XML.

<foo></foo>
<foo />
<foo/>

In practice, some XML processors may create a distinction by interpreting the textual value of <foo></foo> as an empty string and that of <foo /> and <foo/> as null.

Entity references

XML provides two methods for referring to special characters: character entity references and numeric character references.

An entity in XML is a named body of data, usually text, such as an unusual character.

An entity reference is a placeholder that represents that entity. It consists of the entity's name preceded by an ampersand ("&") and followed by a semicolon (";"). XML has five predeclared entities:

* &amp; (&)
* &lt; (<)
* &gt; (>)
* &apos; (')
* &quot; (")

Here is an example using a predeclared XML entity to represent the ampersand in the name "AT&T":

<company-name>AT&amp;T</company-name>

If more entities need to be declared, this is done in the document's Document Type Definition (DTD). A basic example of doing so in a minimal internal DTD follows. Declared entities can describe single characters or pieces of text, and can reference each other.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE example [
<!ENTITY copy "&#xA9;">
<!ENTITY copyright-notice "Copyright &copy; 2006, XYZ Enterprises">
]>
<example>
&copyright-notice;
</example>

When viewed in a suitable browser, the XML document above appears as:

<example> Copyright © 2006, XYZ Enterprises </example>

Numeric character references

Numeric character references look like entity references, but instead of a name, they contain the "#" character followed by a number. The number (in decimal or "x"-prefixed hexadecimal) represents a Unicode code point. Unlike entity references, they are neither predeclared nor do they need to be declared in the document's DTD. They have typically been used to represent characters that are not easily encodable, such as an Arabic character in a document produced on a European computer. The ampersand in the "AT&T" example could also be escaped like this (decimal 38 and hexadecimal 26 both represent the Unicode code point for the "&" character):

<company-name>AT&#38;T</company-name>
<company-name>AT&#x26;T</company-name>

There are many more rules necessary to be sure of writing well-formed XML documents, such as the use of namespaces and the exact characters allowed in an XML name, but this quick tour provides the basics necessary to read and understand many XML documents.

Correctness in an XML document

There are two standard measures of the correctness of an XML document:

* Well-formed. A well-formed document conforms to all of XML's syntax rules. For example, if a non-empty element has an opening tag with no closing tag, it is not well-formed. A document that is not well-formed is not considered to be XML; a parser is not allowed to process it.
* Valid. A valid document has data that conforms to a particular set of user-defined content rules, or XML schemas, that describe correct data values and locations. For example, if an element in a document is required to contain text that can be interpreted as being an integer numeric value, and it instead has the text "hello", is empty, or has other elements in its content, then the document is not valid. To be valid a document must also be well-formed.

Well-formed documents

An XML document is text, which is a sequence of characters. The specification requires support for Unicode encodings UTF-8 and UTF-16 (UTF-32 is not mandatory). The use of other non-Unicode based encodings, such as ISO-8859, is admitted and is indeed widely used and supported.

A well-formed document must conform to the following rules, among others:-

* One and only one root element exists for the document. However, the XML declaration, processing instructions, and comments can precede the root element.
* Non-empty elements are delimited by both a start-tag and an end-tag.
* Empty elements may be marked with an empty-element (self-closing) tag, such as <IAmEmpty />. This is equal to <IAmEmpty></IAmEmpty>.
* All attribute values are quoted, either single (') or double (") quotes. Single quotes close a single quote and double quotes close a double quote.
* Tags may be nested but must not overlap. Each non-root element must be completely contained in another element.
* The document complies to its character set definition. The charset is usually defined in the xml declaration but it can be provided by the transport protocol, such as HTTP. If no charset is defined, usage of a Unicode encoding is assumed, defined by the Unicode Byte Order Mark. If the mark does not exist, UTF-8 is the default.

Element names are case-sensitive. For example, the following is a well-formed matching pair

<Step> ... </Step>

whereas this is not

<Step> ... </step>

The careful choice of names for XML elements will convey the meaning of the data in the markup. This increases human readability while retaining the rigor needed for software parsing.

Choosing meaningful names implies the semantics of elements and attributes to a human reader without reference to external documentation. However, this can lead to verbosity, which complicates authoring and increases file size.

Valid documents

An XML document that complies with a particular schema, in addition to being well-formed, is said to be valid.

An XML schema is a description of a type of XML document, typically expressed in terms of constraints on the structure and content of documents of that type, above and beyond the basic constraints imposed by XML itself. A number of standard and proprietary XML schema languages have emerged for the purpose of formally expressing such schemas, and some of these languages are XML-based, themselves.

Before the advent of generalized data description languages such as SGML and XML, software designers had to define special file formats or small languages to share data between programs. This required writing detailed specifications and special-purpose parsers and writers.

XML's regular structure and strict parsing rules allow software designers to leave parsing to standard tools, and since XML provides a general, data model-oriented framework for the development of application-specific languages, software designers need only concentrate on the development of rules for their data, at relatively high levels of abstraction.

Well-tested tools exist to validate an XML document "against" a schema: the tool automatically verifies whether the document conforms to constraints expressed in the schema. Some of these validation tools are included in XML parsers, and some are packaged separately.

Other usages of schemas exist: XML editors, for instance, can use schemas to support the editing process (by suggesting valid elements and attributes names, etc).

DTD

The oldest schema format for XML is the Document Type Definition (DTD), inherited from SGML. While DTD support is ubiquitous due to its inclusion in the XML 1.0 standard, it is seen as limited for the following reasons:

* It has no support for newer features of XML, most importantly namespaces.
* It lacks expressivity. Certain formal aspects of an XML document cannot be captured in a DTD.
* It uses a custom non-XML syntax, inherited from SGML, to describe the schema.

XML Schema

A newer XML schema language, described by the W3C as the successor of DTDs, is XML Schema, or more informally referred to by the initialism for XML Schema instances, XSD (XML Schema Definition). XSDs are far more powerful than DTDs in describing XML languages. They use a rich datatyping system, allow for more detailed constraints on an XML document's logical structure, and are required to be processed in a more robust validation framework. XSDs also use an XML-based format which makes it possible to use ordinary XML tools to help process them, although WXS (W3C XML Schema) implementations require much more than just the ability to read XML.

Criticisms of WXS include the following:

* The specification is very large, which makes it difficult to understand and implement.
* The XML-based syntax leads to verbosity in schema description, which makes XSDs harder to read and write.
* Schema validation can be an expensive addition to XML parsing, especially for high volume systems.
* The modeling capabilities are very limited, with no ability to allow attributes to influence content models.
* The type derivation model is very limited, in particular that derivation by extension is rarely useful.
* Database-related data transfer has been supported with arcane ideas such as nillability but the requirements of industrial publishing are under-supported.
* The key/keyref/uniqueness mechanisms are not type aware
* The PSVI concept (Post Schema Validation Infoset) does not have a standard XML representation or API, thus it works against vendor independence unless revalidation is performed.

RELAX NG

Another popular schema language for XML is RELAX NG. Initially specified by OASIS, RELAX NG is now also an ISO international standard (as part of DSDL). It has two formats: an XML based syntax and a non-XML compact syntax. The compact syntax aims to increase readability and writability but, since there is a well-defined way to translate the compact syntax to the XML syntax and back again by means of James Clark's Trang conversion tool, the advantage of using standard XML tools is not lost. RELAX NG has a simpler definition and validation framework than XML Schema, making it easier to use and implement. It also has the ability to use datatype framework plug-ins; a RELAX NG schema author, for example, can require values in an XML document to conform to definitions in XML Schema Datatypes.

ISO DSDL and Other Schema Languages

The ISO DSDL (Document Schema Description Languages) standard brings together a comprehensive set of small schema languages, each targeted at specific problems. DSDL includes RELAX NG full and compact syntax, Schematron assertion language, and languages for defining datatypes, character repertoire constraints, renaming and entity expansion, and namespace-based routing of document fragments to different validators. DSDL schema languages do not have the vendor support of XML Schemas yet, and are to some extent a grassroots reaction of industrial publishers to the lack of utility of XML Schemas for publishing.

Some schema languages not only describe the structure of a particular XML format but also offer limited facilities to influence processing of individual XML files that conform to this format. DTDs and XSDs both have this ability; they can for instance provide attribute defaults. RELAX NG and Schematron intentionally do not provide these infoset augmentation facilities.

Displaying XML on the web

Because XML is a data description language, XML documents do not carry information about how to display the data. Without using CSS or XSL, a generic XML document is rendered as raw XML text by most web browsers. Some display it with 'handles' (e.g. + and - signs in the margin) that allow parts of the structure to be expanded or collapsed with mouse-clicks.

In order to style the rendering in a browser with CSS, the XML document must include a reference to the stylesheet:

<?xml-stylesheet type="text/css" href="myStyleSheet.css"?>

Note that this is different from specifying such a stylesheet in HTML, which uses the <link> element.

Extensible Stylesheet Language (XSL) can be used to alter the format of XML data, either into HTML or other formats that are suitable for a browser to display.

To specify client-side XSL Transformation (XSLT), the following processing instruction is required in the XML:

<?xml-stylesheet type="text/xsl" href="myTransform.xslt"?>

Client-side XSLT is supported by many web browsers, but not Opera before version 9.0. An alternative, rather than being dependent on the end-user's browser capabilities, is to use XSL to convert XML into a displayable format on the server. The end-user is not aware of what has gone on 'behind the scenes'; all they see is well-formatted, displayable data.

XML extensions

* XPath makes it possible to refer to individual parts of an XML document. This provides random access to XML data for other technologies, including XSLT, XSL-FO, XQuery etc. XPath expressions can refer to all or part of the text, data and values in XML elements, attributes, processing instructions, comments etc. They can also access the names of elements and attributes. XPaths can be used in both valid and well-formed XML, with and without defined namespaces.
* XQuery is to XML what SQL and PL/SQL are to relational databases: ways to access, manipulate and return XML.
* XML Namespaces enable the same document to contain XML elements and attributes taken from different vocabularies, without any naming collisions occurring.
* XML Signature defines the syntax and processing rules for creating digital signatures on XML content.
* XML Encryption defines the syntax and processing rules for encrypting XML content.
* XPointer is a system for addressing components of XML-based internet media.

Processing XML files

SAX and DOM are object oriented programming APIs widely used to process XML data. The first XML parsers exposed the contents of XML documents to applications as SAX events or DOM objects.

SAX is a lexical, event-driven interface in which a document is read serially and its contents are reported as "callbacks" to various methods on a handler object of the user's design. SAX is fast and efficient to implement, but difficult to use for extracting information at random from the XML, since it tends to burden the application author with keeping track of what part of the document is being processed. It is better suited to situations in which certain types of information are always handled the same way, no matter where they occur in the document.

DOM is an interface-oriented API that allows for navigation of the entire document as if it were a tree of "Node" objects representing the document's contents. A DOM document can be created by a parser, or can be generated manually by users (with limitations). Data types in DOM Nodes are abstract; implementations provide their own programming language-specific bindings. DOM implementations tend to be memory intensive, as they generally require the entire document to be loaded into memory and constructed as a tree of objects before access is allowed.

A form of XML access that has become increasingly popular in recent years is push parsing, which treats the document as if it were a series of items which are being read in sequence. This allows for writing of recursive-descent parsers in which the structure of the code performing the parsing mirrors the structure of the XML being parsed, and intermediate parsed results can be used and accessed as local variables within the methods performing the parsing, or passed down (as method parameters) into lower-level methods, or returned (as method return values) to higher-level methods. For instance, in the Java programming language, the StAX framework can be used to create what is essentially an 'iterator' which sequentially visits the various elements, attributes, and data in an XML document. Code which uses this 'iterator' can test the current item (to tell, for example, whether it is a start or end element, or text), and inspect its attributes (local name, namespace, values of XML attributes, value of text, etc.), and can also request that the iterator be moved to the 'next' item. The code can thus extract information from the document as it traverses it. One significant advantage of push-parsing methods is that they typically are much more speed- and memory-efficient than SAX and DOM styles of parsing XML. Another advantage is that the recursive-descent approach tends to lend itself easily to keeping data as typed local variables in the code doing the parsing, while SAX, for instance, typically requires a parser to manually maintain intermediate data within a stack of elements which are parent elements of the element being parsed. This tends to mean that push-parsing code is often much more straightforward to understand and maintain than SAX parsing code. Some potential disadvantages of push parsing are that it is a newer approach which is not as well known among XML programmers (although it is by far the most common method used for writing compilers and interpreters for languages other than XML), and that most existing push parsers cannot yet perform advanced processing such as XML schema validation as they parse a document.

Another form of XML Processing API is data binding, where XML data is made available as a custom, strongly typed programming language data structure, in contrast to the interface-oriented DOM. Example data binding systems are the Java Architecture for XML Binding (JAXB) and the Strathclyde Novel Architecture for Querying XML (SNAQue).

A filter in the Extensible Stylesheet Language (XSL) family can transform an XML file for displaying or printing.

* XSL-FO is a declarative, XML-based page layout language. An XSL-FO processor can be used to convert an XSL-FO document into another non-XML format, such as PDF.
* XSLT is a declarative, XML-based document transformation language. An XSLT processor can use an XSLT stylesheet as a guide for the conversion of the data tree represented by one XML document into another tree that can then be serialized as XML, HTML, plain text, or any other format supported by the processor.
* XQuery is a W3C language for querying, constructing and transforming XML data.
* XPath is a DOM-like node tree data model and path expression language for selecting data within XML documents. XSL-FO, XSLT and XQuery all make use of XPath. XPath also includes a useful function library.

The native file format of OpenOffice.org, AbiWord, and Apple's iWork applications is XML. Some parts of Microsoft Office 11 will also be able to edit XML files with a user-supplied schema (but not a DTD), and on June 2, 2005 Microsoft announced that, by late 2006 all the files created by users of its Office suite of software will be formatted with web-centered XML specifications. There are dozens of other XML editors available.

Above article originally from wikipedia.org. Above article is available under GNU Free Documentation License.