XML technologies / XML / XML in a Nutshell / XML reference / Fundamentals of XML syntax

(Excerpt from “XML in a Nutshell” by Elliotte Rusty Harold & W. Scott Means)

I.

General syntax structures

II.

DTD (document type definition)

III.

The document body

IV.

Namespaces

  

Each reference section about a particular XML construct includes a less formal description of its syntax. Syntax blocks use these conventions:

Typeface

Meaning

DOCTYPE

Bold indicates text appearing literally as in the XML document, for example DOCTYPE.

Zeichensatzname

Italics indicate placeholders to replace with suitable values. The text describes the replacement, for example Zeichensatzname = en-us.

|

A vertical bar | means choose one value from a list.

[ ]

Square brackets mark an optional part of the syntax.

  

  

 

I. General syntax structures

Every XML document has two main parts: prolog and root element. Some also contain comments or processing instructions after the document element, an informal epilog. The prolog provides structural information about the document, including its XML declaration and DTD. The prolog is optional and may be omitted when DTD validation is unnecessary. Only the top-level document element is mandatory for well-formedness.

These syntax structures apply to the entire document and may occur anywhere unless explicitly stated otherwise.

 

Characters

XML documents are inherently text documents made of characters. For portability across computer systems and support for as many human languages as possible, XML parsers must implement the Unicode standard. Documents need not be stored and edited in Unicode, but the parser must convert their native encoding to Unicode. Every XML parser must support at least UTF-8 or UTF-16 as input encodings.

Note: A major difference between XML 1.0 and XML 1.1 is the definition of allowed Unicode characters. XML 1.0 expressly prohibited many ASCII controls such as BEL and NAK. XML 1.1 permits Unicode characters for these 60 controls, except NUL, x0000, when escaped through numeric character references. XML 1.1 also requires numeric references for C1 controls between 0x0080 and 0x009F, unlike XML 1.0.

 

Whitespace

XML 1.0 defines whitespace as spaces, tabs, carriage returns and line feeds. XML 1.1 also includes NEL (#x85) and the Unicode line separator (#x2028). Whitespace separates syntax components, as in programming languages and ordinary usage. Every whitespace character in element content is significant to an XML parser and passed to the application. Consider:

<p>  Dieser Satz enthält
  belanglose Zeilenenden.</p>

The parser passes the example’s text to the application as follows:

   Dieser Satz enthält
 belanglose Zeilenenden.

Although XML preserves all whitespace in element content, authors can explicitly request preservation of whitespace and formatting characters. See attribute xml:space under “Special attributes”.

To simplify development, parsers normalize every carriage return (#xD) to a single line feed (#xA). A carriage return immediately before a line feed is simply removed, leaving one line-feed character per line ending. XML 1.1 also normalizes these Unicode characters to line feed: #x85 (NEXT LINE, NEL) and #x2028 (LINE SEPARATOR).

  

Names

XML 1.0 names follow these lexical rules:

  • Start with a letter, ideograph, underscore (_) or colon (:).

  • Subsequent characters may only be letters, digits, periods (.), hyphens (-), underscores (_) or colons (:).

A letter here means any Unicode character matching the Letter productions in the XML 1.0 EBNF grammar on page Grammar of an XML 1.0 document.

Note: See the XML 1.1 EBNF production for Name for the characters allowed in XML 1.1 names.

Originally XML 1.0 allowed colons anywhere in names. They are now officially reserved by the recommendation Namespaces in XML (Namespaces in XML). Even without namespaces, use colons only in this sense for compatibility with newer parsers. See “Namespaces” for details on valid namespace identifiers.

Avoid starting names with X, M, L in any case combination unless expressly allowed by an XML specification.

  

Character references

&#dezimalzahl;
&#xhexadezimalzahl;

All XML parsers use Unicode internally, regardless of the encoding declared in the file prolog. Documents could theoretically be created and edited directly in Unicode, but many editors, storage media and communication systems do not support it completely. To let authors use Unicode characters with existing applications, XML provides character references.

A character reference inserts one Unicode character by its decimal or hexadecimal number. Imagine a document containing:

 &#xa9; 2002 O'Reilly &#38; Co 

The parser replaces these references with the corresponding Unicode characters and passes this text to the application:

© 2002 O'Reilly & Co

Character references cannot occur in element or attribute names, but may occur in attribute values. Hexadecimal references are case-insensitive: &xa9; is equivalent to &xA9;.

  

Predefined entities

Besides user-defined entities, XML provides the five named entities in the table. They are predefined and may be used without prior declaration. They form a subset of HTML’s predefined entities:

Table: predefined entities

Entity

Character

XML declaration

&lt;

<

<!ENTITY lt "&#60;">

&gt;

>

<!ENTITY gt "&#62;">

&amp;

&

<!ENTITY amp "&#38;">

&apos;

'

<!ENTITY apos "&#39;">

&quot;

"

<!ENTITY quot "&#34;">

Entities &lt; and &amp; must replace literal < or & in element content and attribute values. Entity &gt; often replaces > in document content, but this is necessary only to avoid the sequence ]]>. Entities &apos; and &quot; are generally used in attribute values to avoid conflicts with the surrounding quotation marks.

Although parsers handle these entities without declarations, you may declare them in the DTD without causing an error.

These special predefined entities create a contradiction: valid documents can reference entities that are technically undeclared. XML actually recommends explicit declarations for older SGML parsers lacking these predefined entities. In practice, this merely adds unnecessary complexity.

  

CDATA sections (text data)

<![CDATA[unkodierte Zeichen & Markup]]>

XML documents consist of markup and text. Characters < and & cannot appear literally in text and must be replaced by character or entity references such as &amp; or &#38;. References prevent the parser from treating < and & as markup; instead it recognizes them as data and passes them to the application.

For larger blocks of text, especially HTML or XML fragments, use CDATA sections. Within a CDATA section, every character between the delimiters is character data. Special characters can be embedded freely, except for the CDATA closing delimiter ]]>.

CDATA sections are useful for embedding XML or HTML examples in tutorials. However, the content of CDATA sections is just plain text to XSLT, DOM or SAX. In the example

 <!CDATA[<a href="mailto:george@whitehouse.gov">The President</a>]]> 

you must therefore extract the email address yourself using string operations if needed.

Warning! CDATA sections cannot nest. The sequence ]]> cannot occur in the text of a CDATA section because it would prematurely end the CDATA section. Usually this is harmless, but remember it when embedding XML as text. To include the closing delimiter of a CDATA section, close the current CDATA section, insert character references, then open another CDATA section for the remaining text.

  

Entities

Think of an entity as a macro: the parser either replaces it, making its text part of XML, or does not, leaving an unparsed entity declaration pointing to external binary data. Parsed entity text may be a literal string or read from an external file. The parser substitutes the declared replacement text and keeps parsing it until no further entity or character references remain.

Two entity types simplify processing in different contexts: general entities and parameter entities. Their reference syntax is almost identical; the main difference is where references are allowed.

Parameter entity references

%name;

When a parser finds a parameter entity reference in the DTD, it substitutes its text. Whether literal or external, it is then processed as part of the document. This has interesting effects on nested references:

<!ENTITY % JAHR "2001">
<!ENTITY COPYRIGHT "&#xa9; %JAHR;">
. . .
<copyright_hinweis>&COPYRIGHT;</copyright_hinweis>

After the required substitutions, the example produces this canonical element:

 <copyright_hinweis>© 2001</copyright_hinweis> 

Warning! Parameter references are treated differently according to their DTD location. References within entity declaration values, such as Copyright &#xa9; %YEAR;, are valid only in an external subset. In the internal subset, parameter references may occur only where complete markup declarations could appear; they can insert only complete declarations.

Parameter entity references are processed only in the DTD. Thus the percent sign % has no special meaning in character data and need not be escaped.

General entity references

&name;

General references are recognized only in parsed text in the document body: between tags and in attribute values. They are not recognized in the DTD, except attribute defaults, or in CDATA sections.

Note: General entity substitution can have interesting side effects. The inserted replacement text is parsed again; any character or general entity references within it are also parsed and substituted.

 

Comments

<!-- Text des Kommentars -->

Comments may occur throughout XML documents and DTDs, but outside other markup tags. Parsers need not preserve their content, so use them only for information applications do not need. Usually it is better to make such information an official part of the application. Rather than storing application data in comments, as often done in HTML, put it in the XML element structure. Use XML comments mainly to clarify complex DTDs or temporarily hide sections.

The sequence -- is forbidden inside comments except as part of the closing delimiter. Since comments cannot nest, you cannot comment out a comment block.

 

Processing instructions

<?target [daten der verarbeitungsanweisung]?>

Processing instructions embed nonvalidated instructions to XML processors. The target of a processing instruction may be any XML name except xml in any case combination; see XML basics. Most often they link to presentation stylesheets. XML separates presentation from data, but needs some linking mechanism. Processing instructions matter only to applications that process them.

Notations identify the kind of processing instruction more precisely. Each application decides whether and how to handle the additional data. Parsers need not respond when an instruction matches a declared notation. With notations, applications unable to interpret an unknown PUBLIC or SYSTEM identifier should recognize that they cannot interpret the data correctly.

 

XML declaration

<?xml version="Versionsnummer" [encoding="Zeichensatzname"] [standalone="yes|no"]?>

The XML declaration identifies the specification version, document encoding and whether the document is self-contained.

Note: To use XML 1.1 features, set pseudo-attribute version to 1.1:

 <?xml version="1.1"?> 

Automatic encoding detection:
The XML declaration, possibly preceded by a Unicode byte-order mark, must come first so the parser can determine the storage encoding. This creates a chicken-and-egg problem with its encoding="..." clause: parsing it requires knowing the encoding. Since the first five characters must be <?xml when a declaration is present, parsers can usually identify the encoding from the first bytes before reading the encoding declaration.

An XML declaration must appear at the beginning. Nothing except perhaps a Unicode byte-order mark may precede its first character (<). Without a declaration, XML 1.0 is assumed.

XML version

... version="Versionsnummer" ...

This attribute identifies the XML specification version. Currently the only possible versions are 1.0 und 1.1.

Encoding declaration

... encoding="Kodierungsname" ...

If present, the encoding declaration identifies the storage encoding. Although parsers internally use Unicode, storage may use any character sets, from an ASCII file using Latin-1 (ISO-8859-1) to a file with Japanese characters.

Parsers may accept other encodings, but XML requires only UTF-8 and UTF-16. Most parsers also support additional encodings.

Standalone declaration

... standalone="yes|no" ...

If a document uses a DTD entirely contained in the document, you may declare standalone="yes". Otherwise the assumed value is no, meaning external entities are read and substituted.

Application developers need not use this flag, but if present its value must be correct. Value standalone="yes" in a document with an external DTD subset violates XML validity constraints.

  

  

 

II. DTD (document type definition)

The section XML basics explained well-formedness and validity. A well-formed document containing a DTD and meeting its rules is valid. A document containing a DTD but violating its rules is invalid. The DTD consists of the internal subset, declarations directly within the XML document, and the external subset, declarations outside it.

 

Parameter entities

Parameter entities provide simple macro substitution only within DTDs. After declaration, they can be referenced from the DTD or other entity declarations. Replacement text is specified directly or by an external file. They simplify maintenance of large, complex documents by letting authors build libraries of components.

 

Declaring parameter entities

<!ENTITY %name "Text, der das Entity ersetzt."> <!ENTITY %name SYSTEM "system-literal"> <!ENTITY %name PUBLIC "pubid-literal" "system-literal" >

Declare parameter entities in the DTD before first use. A declaration contains two items:

  • The entity name used in references

  • Replacement text, directly or through an external entity link

Remember that the parser preprocesses replacement text. It may itself contain parameter references, which are replaced recursively, and character references, replaced immediately. This can have unexpected effects, especially when parameter entities declare other parameter entities. For exact replacement rules and side effects, see Appendix D of the XML 1.0 specification.

 

Parsed general entities

<!ENTITY name "Replacement text."> <!ENTITY name SYSTEM "system-literal"> <!ENTITY name PUBLIC "pubid-literal" "system-literal" >

Parsed general entities are declared in the document type definition and referenced in document text or attribute values. The parser replaces references with entity text, then resumes by processing the newly inserted text.

Their DTD declaration syntax extends that for parameter entities.

Internal entities store replacement text as a literal string entirely within the declaration, needing no external file. This resembles macro processors in many programming languages and environments.

 <!ENTITY name "Erstetzungstext"> 

When a parsed general entity is referenced, its external content is included in the document and parsing resumes with the inserted text.

Note: XML permits two general entity types, parsed and unparsed. An unparsed declaration uses the same syntax with an XML notation name added:
<!ENTITY name SYSTEM "system-literal" notationsname> <!ENTITY name PUBLIC "pubid-literal" "system-literal" notationsname >
Unparsed general entities are not referenced with &name ; syntax. Declare an attribute of type ENTITY or ENTITIES instead. Unparsed external entities are poorly understood, poorly supported and rarely used. We recommend alternatives for external non-XML data, such as XLinks or URI strings.

 

Text declaration

<?xml[ version="Versionsnummer"] encoding="Kodierungsname"?>

External parsed entity files need a text declaration if encoded in something other than UTF-8 or UTF-16, or if using XML 1.1. The replacement text follows. Without a text declaration, XML 1.0 is assumed.

Note: External parsed entities may contain only text data or a well-formed DTD subset. This important restriction prevents distributing arbitrary parts of the XML syntax tree across external parameter entity files for the parser to collect.

 

The external subset

Part or all of the document type declaration may be read from another file. This is the external subset, containing declarations, conditional sections and parameter references. If it uses XML 1.1 or an encoding other than UTF-8 or UTF-16, the external file must begin with a text declaration:

 <?xml[ version="Versionsnummer"] encoding="Kodierungsname"?> 

After the optional declaration come complete DTD markup declarations, including ELEMENT, ATTLIST-, ENTITY and NOTATION declarations, conditional sections and processing instructions. For example:

<!ELEMENT moebelstueck (beschreibung, %weitere_tags; benutzer_tags?, teileliste, montageanleitung+)>

<!ATTLIST moebelstueck xmlns CDATA #FIXED "http://namespaces.oreilly.com/moebel/">
...

Internal DTD subset

The internal subset lies between square brackets ([ and ]) in the document type declaration. It permits declarations and parameter references but no conditional sections. Both subsets may coexist, together forming the complete DTD. Here the internal subset is bracketed:

<!DOCTYPE moebelstueck SYSTEM "moebel.dtd"
[
<!ENTITY % buecherregal_ex SYSTEM "buecherregal_ex.ent">

%buecherregal_ex;

<!ENTITY buecherregal_pic SYSTEM "buecherregal.gif" NDATA gif>
<!ENTITY teileliste SYSTEM "teileliste.ent">
]>

  

Element type declarations

Element type declarations provide a schema for actual instances. They determine whether an element has content and, if so, its type. The following sections describe the possibilities:

Note: Because the namespace recommendation is not explicitly part of XML 1.0, DTD element and attribute declarations must use the complete qualified names expected in the document. When using namespace prefixes, declarations must match the instance exactly. Parameter entities can permit different prefixes, but seamless namespace integration in DTD applications is cumbersome.

  

Empty element types

<!ELEMENT name EMPTY>

An element declared empty can contain neither text nor child elements. Either of these forms is allowed:

<name[attribute="wert"...]/> <name[attribute="wert"...]></name>

  

Unrestricted content

<!ELEMENT name ANY>

Content type ANY is a wildcard: elements may contain text and instances of any DTD-declared element type.

  

Mixed content

<!ELEMENT name (#PCDATA [ |name]+)*> <!ELEMENT name (#PCDATA)>

Declarations containing token #PCDATA permit text, optionally mixed with the child elements listed. With #PCDATA you cannot constrain the number or order of children mixed with text.

  

Constrained child elements

<!ELEMENT name(kind_knoten_mit_regulaerem_ausdruck)[? | * | +]>

XML provides simple regular-expression-like syntax for child order and occurrence counts, using these operators:

Operator

Meaning

Name

Refers to an element with that name.

( ... )

Groups expressions into a sequence, separated by commas, or alternatives, separated by |.

?

The preceding name or expression may occur zero or one time.

*

The preceding name or expression may occur any number of times.

+

The preceding name or expression occurs at least once.

  

 

Attribute-list declarations

<!ATTLIST elementname [attributname attributtyp default-wert-dekl]*>

A valid document must declare the names, types and default values of attributes permitted on each element type.

Attribute names must follow the rules for XML names. No name may appear twice in one declaration.

Attribute declarations specify types, which affect how validating parsers handle instances. This table lists types and meanings:

Attribute type

Meaning

CDATA

Plain text data.

ID

An ID must be unique throughout the document. No two ID attributes may share a value, and no element may have more than one attribute of type ID.

IDREF, IDREFS

One reference to an ID (IDREF) or a whitespace-separated list of references to IDs (IDREFS). Each ID token must reference a valid ID with the same value somewhere in the document.

ENTITY, ENTITIES

One reference to a declared external unparsed entity (ENTITY) or a whitespace-separated list (ENTITIES).

NMTOKEN, NMTOKENS

One name token (NMTOKEN) or a whitespace-separated list (NMTOKENS).

  

The NOTATION attribute type

... NOTATION (notation [| notation]*) ...

The NOTATION attribute mechanism identifies text content obeying formal criteria other than XML. This example uses notations to identify the programming language in element code_fragment:

<?xml version="1.0"?>
<!DOCTYPE code_fragment
[
<!NOTATION java_code PUBLIC "Java-Quellcode">
<!NOTATION c_code PUBLIC "C-Quellcode">
<!NOTATION perl_code PUBLIC "Perl-Quellcode">
<!ELEMENT code_fragment (#PCDATA)>
<!ATTLIST code_fragment
code_lang NOTATION (java_code | c_code | perl_code) #REQUIRED>

]>
<code_fragment code_lang="c_code">
main( ) { printf("Hello, world."); }
</code_fragment>

  

 

Enumerated attribute types

... (name_token [|name_token]*)...

This restricts attribute values to one name token from a list:

<!ELEMENT tuer EMPTY>
<!ATTLIST tuer
zustand (offen | geschlossen | unbekannt) "offen">
. . .
<tuer zustand="geschlossen"/>

  

Default values

You may specify defaults passed to the application when optional attributes are absent. The table lists default specifications and meanings:

Default value

Explanation

#REQUIRED

The attribute must be specified.

#IMPLIED

The attribute may be present or absent.

[#FIXED ] "default-wert"

If absent, the parser supplies the default. When token #FIXED is used, an explicit value must match the default. The parent element always has an attribute of this name.

Modifier #FIXED restricts an attribute to the value specified in its attribute declaration. An explicit value is allowed, though redundant, for an attribute declared #FIXED, provided it exactly matches the #FIXED declaration’s value.

  

 

Special attributes

Some attributes have special XML meanings:

  • xml:space

    Attribute xml:space tells the application whether whitespace in element content matters:

    <!ATTLIST elementname xml:space (default|preserve) default-wert-dekl>
    <!ATTLIST elementname xml:space (default) #FIXED 'default' >
    <!ATTLIST elementname xml:space (preserve) #FIXED 'preserve' >

  • xml:lang

    Attribute xml:lang identifies the element content’s language. In a valid document, the element type declaration must also declare an attribute named xml:lang. See Internationalization for natural-language support details.

  

Notation declarations

<!NOTATION notationsname SYSTEM "system-literal"> <!NOTATION notationsname PUBLIC "pubid-literal"> <!NOTATION notationsname PUBLIC "pubid-literal" "system-literal">

Notation declarations describe the format of unparsed content to the application. They are used by external unparsed entities, processing instructions and some attribute values.

Parsers ignore their meaning but pass them unchanged to the client, including PUBLIC and SYSTEM identifiers, so it can interpret non-XML data and processing instructions correctly.

  

Conditional sections

Conditional declarations include or exclude parts of the external subset. They are forbidden in the internal subset. Example:

<!ENTITY % debug 'IGNORE' >
<!ENTITY % release 'INCLUDE' >

<!ELEMENT addend (#PCDATA)>
<!ELEMENT result (#PCDATA)>

<![%debug;[
<!ELEMENT sum (addend+, result)>
]]>
<![%release;[
<!ELEMENT sum (result)>
]]>

  

  

 

III. The document body

Elements are the foundation of XML, structuring text and attributes into concrete DTD instances. The DTD declarations !ELEMENT and !ATTLIST constrain valid element content. Violating element or attribute combinations cause validation errors.

  

Start-tags and end-tags

<elementname [attributname="attributwert"]*> ...</elementname>

Elements containing text, elements or both must start with a start-tag and end with an end-tag.

  

Empty-element tags

<elementname [attributname="attributwert"]*></elementname> <leeres_element [attributname="attributwert"]* />

Empty elements may use paired tags or empty-element syntax. Both are equivalent, but the latter is shorter and more common.

  

Attributes

attributname="attributwert" attributname='attributwert'

Attribute order is meaningless and parsers need not preserve it. Values require single or double quotation marks and must satisfy the rules on page Constraints.

Whitespace is allowed before and after equals sign (=).

Quoted attribute values are validated according to the type in the element’s !ATTLIST declaration. They may contain general entity references, but not external parsed entity references.

  

  

 

IV. Namespaces

Though not in the original XML 1.0 recommendation, Namespaces in XML became a recommendation less than a year later, on January 14, 1999. Namespaces distinguish names used by different applications. For details see Namespaces.

The following sections explain how namespaces affect element and attribute name construction and interpretation.

  

Unqualified names

name

An unqualified element or attribute name belongs to no namespace, perhaps because neither a namespace prefix nor a default namespace was declared. Unprefixed attributes are always unqualified because no namespace is assigned automatically. Parsers without namespace support, rare today, or configured without it, always pass unqualified names to clients. Two unqualified names are equal if lexically identical.

  

Qualified names

[prefix:]local_part

Qualified names belong to namespaces. There are three kinds:

  • Unprefixed element names within a default namespace declaration’s scope

  • Prefixed element names

  • Prefixed attribute names

Unlike unqualified names, qualified names are equal only if their namespace URIs and local parts match.

  

Default namespace declarations

xmlns="namensraum_URI"

This start-tag attribute associates the element and all unprefixed descendant elements with the URI. An empty value for attribute xmlns cancels default namespaces, leaving unprefixed elements in no namespace.

Note: Default namespaces do not affect unprefixed attributes. Such attributes never belong to a namespace, even when their containing element does.

  

Namespace prefix declarations

xmlns:prefix="namensraum_URI"

This associates a namespace URI with a prefix. The prefix can then qualify the current element and attributes and those within its scope. Nested elements may redefine it for another URI. XML 1.1 documents may undeclare a prefix by assigning an empty string.

  

Back to top

 

 

 

back to top