XML technologies / XML / Python & XML / XML basics / Creating XML documents

(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)

Documents are XML’s heart. Any useful collection of XML text is a document, often stored in a file. Learning to create a well-formed document is an early essential. We examine syntax from individual characters to larger constructs, then those defined for every document by the XML Recommendation.

Characters in XML documents

XML defines a character as an atomic unit of text specified by ISO/IEC 10646, better known as Unicode. Naturally, that is what to say at parties when asked. Standards and XML aim to make documents understandable worldwide. Even simple ASCII characters can become complicated.

The specification includes tab, carriage return and line feed among legal characters alongside Unicode. Writing an XML parser makes character standardization crucial. For most of us, choosing a parser that handles it correctly is enough.

Specify a document’s character encoding in its optional XML declaration:

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

For an external entity that is not a document itself, use a declaration variant called an encoding declaration:

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

More declaration details appear in The document prolog. First consider common character sets and encodings. Any character set mappable to Unicode can be considered a Unicode encoding even if it cannot represent all Unicode characters.

The ASCII character set

ASCII, the American Standard Code for Information Interchange, is a seven-bit format: seven zeros or ones per character. Nearly every computer understands it. Unicode extends ASCII, keeping the first 128 characters identical.

The ISO-8859-1 character set

Character set ISO-8859-1 is also known as Latin-1. Widespread ISO-8859-1 supports most Western European languages, though not all. Unicode’s first 256 characters match it for compatibility; its first 128 match ASCII. The remaining 128 mix controls, special characters and diacritics. It drew inspiration from DEC’s Multinational Character Set but differs in places. Other ISO-8859-X sets cover more languages and characters.

UTF-8 encoding

UTF-8, the Universal Transformation Format, eight-bit, is documented in F. Yergeau’s IETF RFC 2279. It is the most popular complete Unicode encoding.

UTF-8 extends ASCII: its first 128 positions transparently encode ASCII. Unicode supports over two billion characters, far beyond 128, requiring encoding into eight-bit bytes. UTF-8 assigns unique byte sequences: ASCII uses one byte and other characters two or more. Its XML declaration looks like:

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

The RFC details UTF-8 handling.

 

Text, character data and markup

The specification says: “Text consists of intermingled character data and markup.” Every character is either character data, the useful information such as addresses or quantities, or markup: special characters for tags, entities, comments, CDATA delimiters, DTDs, processing instructions and declarations. Together they form text.

Character data in element content means strings without opening markup delimiters. Distinguishing them matters: markup lets programs interpret the data.

All markup begins with either less-than (<) or ampersand (&). Less-than markup ends with greater-than (>); ampersand markup ends with semicolon (;). Usually these are the only special characters to know. Sometimes single (') and double (") quotes need care. They are allowed in data but may need special encoding. Any Unicode character can occur in character data.

Thus ampersands (&) and angle brackets (<, >) cannot be used literally. This would confuse a processor:

 <question>Ist 5 < 7 ≤ 9?</question> 

The content of element question contains forbidden characters. The < must begin markup, so the following space is a syntax error. Less-than starts constructs, most often tags; ampersand marks entity references.

Encode these characters using entities or character references. Correct XML for the example is:

 <question>Ist 5 &lt; 7 &#x2263; 9?</question> 

Entity references are covered later, but HTML users already know examples such as &apos; ('), &quot; ("), &lt; (<) and &gt; (>). XML allows custom entities containing more than one character, but these four are predefined and need no document declaration. Character references differ by identifying individual Unicode characters without mnemonic names. For example, a character reference familiar from HTML is &#174; (®, registered trademark). XML also allows hexadecimal digits by inserting x between hash and first digit. Thus reference &#xAE; identifies the registered trademark symbol too. Authors cannot define character references: they always refer to Unicode-assigned numbers.

 

Names

XML defines lexical details, especially names. Names are tokens combining legal letters, digits, underscores, hyphens and colons. They cannot start with a digit. They name elements, attributes, entities and everything needing a name. Some names are reserved: those starting with xml in any case combination are reserved for standardization or future specifications. Avoid colons (:) in names, since namespaces use them for prefix tokens identifying a domain context. XML 1.0 allows colons, but newer namespace specifications restrict their syntax. For book-related elements such as bookTitle or bookAuthor, use capitalization, hyphens or underscores to separate words, for example book_Title, book-Title or bookTitle, instead of colons as in book:Title. An expression like book:Title suggests an element named Title within the namespace URI attached to the local book. Of course, namespaces might be right for you; then read the namespace specification carefully and define what you need.

Whitespace in character data

When working with XML-based markup languages, deciding how to handle whitespace can be difficult. Many applications can treat it as ordinary character data; others cannot. The issue usually arises when an application controls presentation to the user. The XML specification does not attempt to solve it, but provides a way to tell tools and applications that whitespace in a particular element should be preserved rather than treated as flexible spacing.

The simplest illustration is the usual display of program source code in HTML. Most HTML authors place source code in a pre element:

<pre>
def hello( ):
   print "Hallo, Welt!"
</pre>

This is certainly the simplest way to display source code in HTML. Now consider what happens when we replace the pre element with a paragraph, a p element:

<p>
def hello( ):
   print "Hallo, Welt!"
</p>

Most browsers produce a very different result: the entire program normally appears on one line with just one space between words, although the example contains several lines and consecutive spaces.

The solution seems simple, at least for HTML: use a pre element to preserve whitespace. Unfortunately this obvious solution has an equally obvious problem: it only works for HTML, not arbitrary XML-based markup languages. We need a solution like the following that also works for non-HTML documents:

<Poem>
   Ode to a node,
   Nested beneath its tree,
   Snug as a bug in its XML rug
   Dreaming of the W3C.
</Poem>

How should an XML tool know that the line endings and layout of the poem matter?

The XML specification defines an attribute named xml:space that you can attach to an element to tell the application to preserve whitespace. The client application is responsible for acting on this information and actually preserving whitespace when processing or formatting data. A typical XML parser passes document whitespace to the application whether or not it has seen the xml:space attribute in the document or schema. The application can use it to decide how to manipulate document content.

The value of the xml:space attribute can be either default or preserve. With default the application may handle whitespace as it normally would; XML places no restrictions on this. However, with preserve the application is expected to respect whitespace in the element where the attribute applies and all its descendants until it encounters a child defining a value for xml:space. From that point, the child’s xml:space value takes precedence for that child and its descendants.

The xml:space attribute can be used in several ways. First, simply insert it in the document instance, which suffices for well-formed XML. The first line of our poem then becomes:

 <Poem xml:space="preserve"> 

This seems reasonable for small amounts of XML, but does not scale to large collections of documents edited by people. Imagine what HTML would look like if a special attribute were always required to obtain the effect of the pre element! Therefore the xml:space attribute is usually added to the document schema. In a DTD we would write:

<!ATTLIST Poem xml:space (default|preserve) 'preserve'> 

Attribute-list declarations are explained in more detail later under Attribute declarations.

In practice, most applications parsing XML infer from element names how to handle their character data. For example, while parsing a book in XML, you may encounter a code element indicating that whitespace in this section should be preserved. On closer inspection, the document type often specifies that xml:space has a default of preserve for these elements.

Handling line endings

The specification is explicit about line endings. An XML parser must pass characters to an application with normalized line endings. Thus all combinations of the hexadecimal characters 0x0D and 0x0A or single 0x0D characters not followed by 0x0A are converted into a single 0x0A character. For those less familiar with hexadecimal, this means typical formatting codes such as \r\n and \r become \n. And if you have never used those strange backslashes, text from platforms normally ending lines with carriage return and line feed, such as Windows, is converted to use only line feed.

Language identification

The specification provides an attribute named xml:lang for identifying the language used in documents. Again, it must be declared in valid documents, much like xml:space. Permitted values are defined by IETF RFC 1766 or a later revision. Most language codes have two letters, such as en for English, but dialects can be specified with an underscore and two more letters. American English can therefore be indicated by en_US and British English by en_GB.

 

The document prolog

An XML document has a prolog containing everything before the single element holding the document content. It consists of an optional XML declaration, followed by an optional document type declaration and any number, including zero, of comments and processing instructions. The prolog may thus be empty, but often includes an XML declaration as a sign of good form. A document type declaration is needed for conformance to a DTD.

The XML declaration resembles a processing instruction but differs because of its purpose. XML requires documents to use Unicode without constraining how characters are encoded as bytes in the document stream, so the encoding must be determined. Some encodings can be recognized from the first bytes, using specific rules in the XML Recommendation. Many cannot. If the encoding is not known in advance, for example from an HTTP response header, the specification requires UTF-8 or an XML declaration identifying the encoding. The declaration always includes the XML specification version to which the document conforms; so far only XML 1.0 has been defined. A typical declaration is:

 <?xml version="1.0" encoding="iso-8859-1"?> 

This declares ISO 8859-1, better known as Latin-1. Omitting the encoding is entirely legal, yielding this minimal declaration:

 <?xml version="1.0"?> 

Surely this is already printed on coffee mugs.

The XML declaration may be followed by a document type declaration. Note that this differs from a document type definition although their first two words and abbreviations are identical. To avoid confusion, DTD never abbreviates the declaration, which is usually called a DOCTYPE declaration. It names the document element and may also specify internal and external DTD components. Here is its simplest form:

 <!DOCTYPE book> 

This only tells us that the document element has type book; by itself, that is not very useful. Two additional components are available. Both are optional, but one or both are needed to make the declaration meaningful. This example includes both:

<!DOCTYPE book SYSTEM "http://xml.example.com/dtds/book.dtd" [
   <!ENTITY myCompany "Super Mega Ultra Corporation">
  ]>

This specifies an external DTD subset, the string SYSTEM and the quoted string, plus an internal subset in square brackets.

If a document type declaration exists, its name must match the root element. If you declare the document type as <!DOCTYPE Tool [...]> the root element must be Tool. All DTD constraints on nesting, character data and attributes must also be enforced for the document to pass validation.

When both internal and external subsets are used, the internal subset takes precedence: rules inside the XML document override rules for the same construct in the external DTD subset.

Start-tags, end-tags and empty-element tags

An element’s name indicates its type. Attributes in a start-tag are not recognized in any particular order. The specification makes no distinction between <name first="Chris" last="Jones"> and <name last = "Jones" first = "Chris">.

There are several tag restrictions to know. First, attributes must be unique: an attribute name cannot appear twice in one start-tag. For a valid document, attributes must also be declared and their values must match the declared types. Attribute values cannot be or contain external entity references. Finally, neither an attribute in a start-tag nor its entity replacement text may contain <. End-tag names must match their start-tag names; attributes are forbidden in end-tags.

Elements can contain almost any character data, provided it does not conflict with the surrounding markup, as discussed under Text, character data and markup.

Empty elements have no content, but may have attributes, as shown here:

<names>
   <name first="Chris" last="Jones"/>
   <name/>
</names>

This XML represents two well-formed name elements. Both are empty, but the first has two attributes.

Quoting attribute values

The specification defines literals as quoted strings that do not contain the quotation mark used as their delimiter. Literals specify internal entity content and attribute values. Typical attribute/value combinations look like this:

 <account refnum="23908403"/> 

Here, refnum is an attribute of the account element with value 23908403. Either single or double quotation marks are allowed, provided the delimiter itself does not appear directly in the value. It may appear through entity or numeric character references.

For an attribute value containing both kinds of quotation marks, consider this sentence:

Die Katze sagte: "Der Hund schrie 'Hilfe!', dann schlug ich zu."

Encoded as an attribute, it becomes:

<talltale text='Die Katze sagte: "Der Hund schrie &apos;Hilfe!&apos;, dann schlug ich zu."'/>

Comments

XML comments resemble HTML comments. The specification allows them anywhere outside other markup. A simple XML comment looks like this:

<!-- Dies ist ein Kommentar. -->

Since comments cannot occur inside other markup, you cannot place one inside an XML start-tag:

 <book name="Python und XML" <!--Kommentar hier-->> 

XML forbids this construction. Interestingly, comments can occur in a DTD. They are not considered document character data. Another restriction is that double hyphens (--) cannot appear in comment text, because --> marks the comment’s end. To avoid syntactic problems of earlier markup languages, XML simply prohibits double hyphens in comments. Entities and other markup are not processed inside comments, so normally special XML characters can occur without causing syntax errors. The corrected version of the previous element is:

<book name="Python und XML">
   Dieses Buch handelt von der Programmiersprache Python und der Markup-Sprache XML.
   <!--Kommentar hier-->
</book>

Placing the comment inside the element rather than its start-tag now satisfies the rules.

Processing instructions

Processing instructions (Processing Instructions, or PIs) let an XML document pass instructions to a processing application. The XML processor does not consider them character data. Their purpose is to convey information to an application. For example, an important message could ask the receiving application to alert the user using the following instruction. Different applications could respond differently: a Palm VII might beep, while an X Window application might open an alert dialog.

 <?newsAlert title="Invasion von Marsmenschen"?> 

In this example, newsAlert is normally called the target; the rest has no special name. This distinction is conventional: the specification only requires <? at the beginning, ?> at the end, and no ?> inside the PI. Most APIs call these two parts target and data. There is no special content syntax, but starting with a target, usually the processing tool’s name, is recommended. Applications increasingly expect attribute/value pairs after the target, often called pseudo-attributes. They may handle or ignore the PI as they choose. PIs provide an XML-oriented way to pass events between applications or annotate data for particular applications. Historically, the SGML community used PIs to encode instructions for formatters, with meanings such as “Insert a page break here.”

CDATA sections

A CDATA section protects special characters in document character data. For example:

 <![CDATA[Julius <aesar & Ma<beth]]> 

This actually encodes the character data:

 Julius <aesar & Ma<beth 

Without a CDATA section, general entities or character references must encode it:

Julius &lt;aesar &amp; Ma&lt;beth 

CDATA sections conveniently protect large amounts of text containing characters that would otherwise be treated as markup. A section begins with <![CDATA[; no whitespace is allowed around CDATA. Inside a CDATA section, no XML syntax is recognized until ]]> is reached. Entity and character references are neither resolved nor recognized, so the text &#173; is not replaced by the registered trademark symbol, although it would be in ordinary character data or a CDATA attribute value.

  

 

 

 

back to top