Well-formed documents: XML syntax

As long as only well-formedness is required, XML is a generic framework for storing any amount of text or any data whose structure can be represented as a tree. The only indispensable syntactical requirement is that the document has exactly one root element (alternatively called the document element). This means that the text must be enclosed between a root start-tag and a corresponding end-tag. The following is a "well-formed" XML document:

<book>This is a book.... </book> 

The root element can be preceded by an optional XML declaration. This element states what version of XML is in use (normally 1.0); it may also contain information about character encoding and external dependencies.

<?xml version="1.0" encoding="UTF-8"?> 

The specification requires that processors of XML support the pan-Unicode character encodings UTF-8 and UTF-16 (UTF-32 is not mandatory). The use of more limited encodings, such as those based on ISO/IEC 8859, is acknowledged and is widely used and supported.

Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA.

XML comments start with <!-- and end with -->. Two dashes (--) may not appear anywhere in the text of the comment.

<!-- This is a comment. --> 

In any meaningful application, additional markup is used to structure the contents of the XML document. The text enclosed by the root tags may contain an arbitrary number of XML elements. The basic syntax for one element is:

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

The two instances of »name« are referred to as the start-tag and end-tag, respectively. Here, »content« is some text which may again contain XML elements. So, a generic XML document contains a tree-based data structure. Here is an example of a structured XML document:

<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.</step>
<step>Knead thoroughly.</step>
<step>Cover with a cloth, and leave for one hour in warm room.</step>
<step>Knead again.</step>
<step>Place in a bread baking tin.</step>
<step>Cover with a cloth, and leave for one hour in warm room.</step>
<step>Bake in the oven at 350(degrees)F for 30 minutes.</step>
</instructions>
</recipe>

Attribute values must always be quoted, using single or double quotes; and each attribute name must appear only once in any element.

XML requires that elements be properly nested — elements may never overlap, and so must be closed in the opposite order to which they are opened. For example, this fragment of code below cannot be part of a well-formed XML document because the title and author elements are closed in the wrong order:

<!-- WRONG! NOT WELL-FORMED XML! -->
<title>Book on Logic<author>Aristotle</title></author>

One way of writing the same information in a way which could be incorporated into a well-formed XML document is as follows:

<!-- Correct: well-formed XML fragment. -->
<title>Book on Logic</title> <author>Aristotle</author>

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-element tag. An empty-element tag resembles a start-tag but contains a slash just before the closing angle bracket. The following three examples are equivalent in XML:

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

An empty-element may contain attributes:

<info author="John Smith" genre="science-fiction" date="2009-Jan-01" /> 

Entity references

An entity in XML is a named body of data, usually text. Entities are often used to represent single characters that cannot easily be entered on the keyboard; they are also used to represent pieces of standard ("boilerplate") text that occur in many documents, especially if there is a need to allow such text to be changed in one place only.

Special characters can be represented either using entity references, or by means of numeric character references. An example of a numeric character reference is "&#x20AC;", which refers to the Euro symbol by means of its Unicode codepoint in hexadecimal.

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; & ampersand
&lt; < less than
&gt; > greater than
&apos; ' apostrophe
&quot; " quotation mark

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> 

Additional entities (beyond the predefined ones) can be declared 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>

Similarly, in the previous example, notice that "&#xA9" is used to generate the "©" symbol.

Well-formed documents

In XML, a well-formed document must conform to the following rules, among others:

  • 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 with 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 with its declared character encoding. The encoding may be declared or implied externally, such as in "Content-Type" headers when a document is transported via HTTP, or internally, using explicit markup at the very beginning of the document. When no such declaration exists, a Unicode encoding is assumed, as defined by a Unicode Byte Order Mark before the document's first character. If the mark does not exist, UTF-8 encoding is assumed.

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

<Step> ... </Step>

whereas this is not

<Step> ... </step>

By carefully choosing the names of the XML elements one may 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.

Automatic verification

It is relatively simple to verify that a document is well-formed or validated XML, because the rules of well-formedness and validation of XML are designed for portability of tools. The idea is that any tool designed to work with XML files will be able to work with XML files written in any XML language (or XML application). One example of using an independent tool follows:

  • load it into an XML-capable browser, such as Firefox or Internet Explorer
  • use a tool like xmlwf (usually bundled with expat)
  • parse the document, for instance in Ruby:
irb> require "rexml/document"
irb> include REXML
irb> doc = Document.new(File.new("test.xml")).root

No comments:

Post a Comment