What Makes an XML Document Well-Formed?

An XML document achieves the status of being well-formed by adhering strictly to the universal syntax rules defined by the W3C XML standard. Unlike standard HTML, which is forgiving of structural and syntax errors, XML enforces rigid formatting. If a document violates even a single structural rule, an XML parser will stop processing and return a fatal error. This article outlines the essential syntax requirements an XML document must meet to be considered well-formed.

1. A Single Root Element

Every well-formed XML document must have exactly one root element (also called the document element). This element acts as the parent container that encloses all other elements, data, and comments.

<root>
    <child>Content</child>
</root>

2. Properly Closed Elements

Every element that is opened must be explicitly closed with a matching end tag. Empty elements must use self-closing syntax.

3. Correct Nesting of Elements

XML elements must nest cleanly within each other. Tags cannot overlap; an inner tag must be closed before the outer tag that contains it is closed.

4. Case-Sensitive Tag Names

XML is strictly case-sensitive. The opening and closing tags must match in letter casing precisely.

5. Quoted Attribute Values

All element attributes must have their values enclosed in quotation marks (either single or double quotes). Attribute minimization (boolean attributes without explicit values) is not permitted.

6. Proper Use of Predefined Entities

Certain characters are reserved for XML markup syntax and cannot appear as raw text within element content or attribute values. These must be replaced with their corresponding predefined entity references:

Alternatively, raw blocks of text containing these characters can be enclosed within <![CDATA[ ... ]]> sections.

7. Position of the XML Declaration

If an XML declaration (prolog) is included, it must appear on the very first line of the document with no preceding characters or whitespace.

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

8. Valid Naming Rules

Element and attribute names must follow specific naming conventions: * Names can contain letters, numbers, hyphens, underscores, and periods. * Names cannot start with a number or punctuation character. * Names cannot start with the letters “xml” (in any combination of uppercase or lowercase). * Names cannot contain spaces.