XML File Documentation


Summary

An Extensible Markup Language file stores data as nested, custom-named tags in plain Unicode text. You define the tags yourself, and strict rules (one root element, every tag closed and correctly nested, case-sensitive) keep it reliably parseable. The W3C published XML 1.0 in 1998. A .xml file opens in any text editor or browser; its MIME type is application/xml.

Technical details

FeatureValue
Full nameExtensible Markup Language
File extension.xml
MIME typeapplication/xml, text/xml
Format typePlain-text, tag-based markup
DeveloperW3C (World Wide Web Consortium)
Introduced1998 (XML 1.0, 10 February 1998)
StandardW3C XML 1.0 (Fifth Edition, 26 November 2008)
Open standardYes — royalty-free W3C Recommendation
Derived fromSGML (ISO 8879), a simplified subset
EncodingUTF-8 (default), UTF-16; declared in the prolog
Optional declaration<?xml version="1.0" encoding="UTF-8"?>
Root elementRequired — exactly one wraps the whole document
Case sensitiveYes — <Name> and <name> differ
NamespacesSupported via xmlns / xmlns:prefix
Predefined entities&lt; &gt; &amp; &apos; &quot;
CDATA sectionsSupported — <![CDATA[ ... ]]> holds literal text
CommentsSupported — <!-- ... -->
Schema languagesDTD (built in), XSD (XML Schema)
Query / transformXPath, XQuery, XSLT
Security risksXXE (external entities), billion-laughs entity expansion
Related extensions.xsd .xsl .dtd .svg .html .json
Specificationw3.org/TR/xml/
Structure at a glance

XML is plain Unicode text, normally UTF-8. A file may begin with the declaration <?xml version="1.0" encoding="UTF-8"?>, but it is optional; when present it must be the very first thing in the file. A single root element wraps everything below it. Every tag must close (<a>...</a> or the empty form <a/>) and nest correctly, tag names are case-sensitive, and attribute values are quoted (id="7"). Five predefined entities escape reserved characters in text: &lt;, &gt;, &amp;, &apos;, &quot;.

What is an XML file?

XML stands for Extensible Markup Language. It is a plain-text format for storing and moving structured data, defined by the World Wide Web Consortium and published as the XML 1.0 Recommendation on 10 February 1998. The current text is the Fifth Edition (26 November 2008). XML is a simplified subset of SGML (ISO 8879, the older Standard Generalized Markup Language), trimmed down so it could be read by both people and machines without SGML’s complexity.

The “extensible” part is the whole point. HTML has a fixed vocabulary of tags for describing web pages; XML defines no tags of its own. You invent elements that fit your data (<invoice>, <book>, <config>) and the rules stay the same regardless of which tags you choose. Those rules are strict and case-sensitive, which is exactly what lets one program reliably read a file another program wrote. XML underpins a large family of formats: SVG vector graphics, RSS and Atom feeds, SOAP and SAML, sitemaps, Android layouts, Maven pom.xml and .NET project files. The .docx and .xlsx you open in Office are ZIP archives full of XML parts. Everything below describes how the text is actually structured.

The XML declaration and prolog

An XML file may open with a declaration. When it is present it must be the very first thing in the file, with nothing (not even whitespace or a comment) before it:

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

This looks like a tag but it is not an element; the three items inside are called pseudo-attributes. version is required and is almost always 1.0 (XML 1.1 exists but is rarely used). encoding is optional and names the character encoding of the bytes that follow, such as UTF-8 or UTF-16. standalone is optional and takes only yes or no: yes declares that no external markup declarations (an external DTD, for example) affect the document’s content.

The declaration itself is optional. A perfectly valid file can begin straight with its root element. If the declaration is omitted, a parser assumes UTF-8 or UTF-16 and detects which by inspecting the first bytes. An optional byte order mark can precede the text: EF BB BF for UTF-8, or FF FE / FE FF for UTF-16, and the parser uses it to lock the encoding. Because the file is text, there is no fixed magic number; when a declaration is present the file simply starts with the bytes 3C 3F 78 6D 6C, which is the ASCII for <?xml. The region from the declaration up to the root element (declaration, comments, processing instructions, an optional <!DOCTYPE>) is called the prolog.

Elements, tags, and the single root

The body of the document is a tree of elements. An element is written as a start tag, some content, and a matching end tag: <title>War and Peace</title>. An element with no content can use the empty-element form, a single tag closed with a slash: <break/> means the same as <break></break>. Elements nest to form the hierarchy, and one element, the root, contains all the others.

<?xml version="1.0" encoding="UTF-8"?>
<library>
  <book id="b1" lang="en">
    <title>War and Peace</title>
    <author>Leo Tolstoy</author>
    <pages>1225</pages>
    <cover/>
  </book>
</library>

A document that obeys the grammar is well-formed. The core rules are short and non-negotiable: there is exactly one root element; every start tag has a matching end tag (or is an empty-element tag); elements are nested, never overlapping, so <a><b></a></b> is illegal; tag names are case-sensitive, so <Book> does not close <book>; and every attribute value is quoted. A parser that hits any violation stops with a fatal error and refuses to process the rest, which is why the “XML parsing error” you sometimes see is unforgiving compared with HTML’s lenient rendering.

Attributes: name-value pairs on elements

Elements carry attributes inside the start tag, written as name="value". In <book id="b1" lang="en"> the element has two attributes. The value must be quoted, with either single or double quotes, and each attribute name may appear at most once on a given element: <book id="b1" id="b2"> is not well-formed. Attribute values are always strings; XML has no notion of a numeric or boolean attribute at the syntax level, so pages="1225" is text that your schema or program interprets as a number.

Whether a piece of data belongs in an attribute or a child element is a modelling choice, not a rule. Attributes suit small, singular, metadata-like values (an id, a language code, a unit). Child elements suit data that can repeat, contain further structure, or grow over time. A rough guide: if you might later need a list of it, or sub-parts of it, make it an element; attributes cannot nest or repeat.

Predefined entities and character references

Some characters cannot appear literally in content because they mark up the document. A raw < would start a tag and a raw & would start an entity. XML defines five predefined entities that stand in for these characters:

EntityCharacterName
&lt;<less-than
&gt;>greater-than
&amp;&ampersand
&apos;'apostrophe
&quot;"quotation mark

So if (x &lt; 3 &amp;&amp; y) in the source is read back as if (x < 3 && y). Any Unicode character can also be written as a numeric character reference: &#169; (decimal) or &#xA9; (hexadecimal) both produce the copyright sign. Beyond the five built-ins, a document can declare its own custom entities in a DTD with <!ENTITY name "replacement"> and then reference them as &name;. Internal entities keep their replacement text inside the document; external entities pull it from elsewhere with a SYSTEM (a URI) or PUBLIC identifier. External entities are also where the security problems below begin.

CDATA sections, comments, and processing instructions

Escaping every < and & is tedious when you need to embed a block of code or markup as literal text. A CDATA section tells the parser to treat everything inside as raw character data, with no markup recognised:

<script><![CDATA[
  if (a < b && c > d) { run(); }
]]></script>

Inside <![CDATA[ ... ]]> the characters < and & lose their special meaning and pass through unchanged. The one thing a CDATA section cannot contain is the terminator sequence ]]> itself, because that closes the section; to include those literal characters you split them across two sections or escape the > as &gt;. (In ordinary content the spec also requires the > in a stray ]]> to be escaped, for compatibility.)

Comments are written <!-- like this --> and are ignored by the parser; the string -- may not appear inside one. Processing instructions carry data for a specific application, written <?target data?>. The common example is the stylesheet link a browser uses to render a feed or document: <?xml-stylesheet type="text/xsl" href="style.xsl"?>. The processing instruction target xml is reserved for the declaration.

Namespaces: xmlns, prefixes, and the namespace URI

When you merge XML from two sources, both might define a <table> element that mean different things. Namespaces resolve the clash by attaching each element name to a unique identifier. You declare a namespace with an xmlns attribute, either as a default (applying to an element and its descendants) or bound to a prefix:

<root xmlns:html="http://www.w3.org/1999/xhtml"
      xmlns:company="http://example.com/inventory">
  <html:table>
    <html:tr><html:td>Data</html:td></html:tr>
  </html:table>
  <company:table>
    <company:entry>Data</company:entry>
  </company:table>
</root>

Here html:table and company:table are distinct because their prefixes map to different namespaces. The combination of prefix and local name (html:td) is a qualified name. The value of the namespace declaration, http://www.w3.org/1999/xhtml, is a namespace URI, and this is the part people misread. It is only an identifier: a globally unique string used to tell vocabularies apart. Nothing fetches it, and it need not point at a real page. A URL is used purely because URLs are a convenient way to guarantee uniqueness under a domain you control.

Well-formed versus valid: DTD and XSD

Being well-formed only means the syntax is correct. A document is valid when it also matches a declared grammar that says which elements are allowed, in what order, and with which attributes. XML has two schema languages for this.

A DTD (Document Type Definition) is the original mechanism, declared with <!DOCTYPE> either inline or via an external file. It uses <!ELEMENT> to declare an element’s allowed content model and <!ATTLIST> to declare its attributes:

<!DOCTYPE library [
  <!ELEMENT library (book+)>
  <!ELEMENT book (title, author, pages)>
  <!ELEMENT title (#PCDATA)>
  <!ATTLIST book id ID #REQUIRED>
]>

DTDs are compact but limited: they are not themselves XML, they have no real data types (everything is text), and they predate namespaces. XSD (XML Schema Definition, see XSD) replaced them for most serious work. An XSD is written in XML, is namespace-aware, and brings a full type system: xs:integer, xs:date, xs:decimal and dozens more, plus cardinality controls (minOccurs, maxOccurs) and reusable complex types. A validating parser checks the instance document against the schema and reports every element that breaks a rule. Separately, XPath addresses nodes in the tree with path expressions, XQuery runs queries over XML, and XSLT transforms one XML document into another format such as HTML or plain text; all three read the same element tree described above, but none change the storage format itself.

Frequently asked questions

Well-formed versus valid, what is the difference?

Well-formed means the syntax obeys XML’s grammar: one root, every tag closed and nested, quoted attributes. Any parser can check that with no extra files. Valid is a stronger claim: the document is well-formed and conforms to a specific schema (a DTD or an XSD) that dictates which elements and attributes are allowed and in what shape. A file can be well-formed but invalid, for example if it is missing an element the schema requires.

Why do I get an “XML parsing error”?

The document is not well-formed, so the parser stops. The usual causes are an unclosed or mismatched tag, a raw & or < in text that should have been written &amp; or &lt;, a missing root element, or a mismatch between the declared encoding and the actual bytes. Opening the file in a browser or in a code editor points to the offending line and column.

What is a namespace URI actually for?

It is a unique name, nothing more. A namespace URI such as http://www.w3.org/1999/xhtml exists only to make two vocabularies distinguishable, so an html:table is never confused with someone else’s table. The parser does not download it, and it can be a URI that resolves to nothing. Domains are used because they are already globally unique.

Are .docx and .xlsx really XML?

Effectively yes. Office Open XML files are ZIP archives, and inside each one are several XML parts describing the document body, styles, and relationships, alongside any embedded images. Rename a .docx to .zip, open it, and you will find files like document.xml. The .docx is the package; the XML is the content. For lightweight data exchange, many APIs instead use JSON, which is terser but has no namespaces, schemas, or mixed content.

References