What is an XML file and how is it formatted?

Dark navy cover card with the title 'What is an XML file and how is it formatted?' in white and a green accent bar

An XML file is a plain-text file that stores data inside tags you name yourself, like <order> or <customer>. XML (Extensible Markup Language) is formatted as a tree: an optional declaration on the first line, then exactly one root element that contains every other element, with each start tag closed, tags nested in order and attribute values in quotes.

What an XML file looks like

A small but complete XML file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!-- A customer order exported from a shop -->
<order status="paid">
  <customer>
    <name>Ada Lovelace</name>
    <email>ada@example.com</email>
  </customer>
  <items>
    <item sku="BOOK-A">Notes on the Analytical Engine</item>
    <item sku="PEN-B">Fountain pen</item>
  </items>
  <gift/>
</order>

Every name here (order, customer, sku) was made up for this file. That is the "extensible" part: as MDN's XML introduction puts it, XML is like HTML but without predefined tags, so you define your own. A program reading the file learns what each value means from the tag around it.

The parts of an XML document

An XML document is built from a handful of pieces, and each one has a fixed spelling.

  • Declaration. <?xml version="1.0" encoding="UTF-8"?> names the XML version and character encoding. The XML 1.0 specification says documents SHOULD begin with it, so it is recommended rather than required.
  • Root element. <order> wraps everything else. There is exactly one.
  • Elements. A start tag, content and an end tag: <name>Ada Lovelace</name>. Elements can hold text, other elements or both.
  • Empty elements. <gift/> is shorthand for <gift></gift>.
  • Attributes. Name and value pairs inside a start tag, such as status="paid".
  • Comments. <!-- like this -->.
  • Entities. Escapes for characters that would otherwise look like markup.

The formatting rules a parser enforces

An XML parser accepts a file only if it is well-formed, and the W3C specification treats every broken rule as a fatal error. Browsers quietly repair bad HTML; an XML parser stops. The rules that trip people up most:

  1. One root element. Section 2.1 of the spec says there is "exactly one element, called the root". Two top-level <item> elements side by side is an error.
  2. Close every tag, in order. Elements must "nest properly within each other", so <b><i>text</b></i> fails.
  3. Names are case-sensitive. The spec does no case folding, so <Name> and </name> don't match.
  4. Quote attribute values. sku=BOOK-A without quotes is an error, and the same attribute can't appear twice on one tag.
  5. Escape < and & in text. Write &lt; and &amp; instead.
  6. No -- inside a comment. The spec forbids the double hyphen there.

The five predefined entities

XML ships with exactly 5 named entities. Anything else must be declared in a DTD or written as a numeric reference like &#xA9; for ©.

Entity Character
&lt; <
&gt; >
&amp; &
&quot; "
&apos; '

When a block of text is full of these characters, such as a code sample, a CDATA section saves you from escaping each one: <![CDATA[ if (a < b && c) ]]>. CDATA sections can't nest.

Well-formed vs valid XML

Well-formed XML follows the syntax rules above, and valid XML also follows a schema. A schema, written as a DTD or an XML Schema, lists which elements and attributes a particular kind of document may contain. MDN's example is a <warning> tag that nobody defined: the file is still well-formed, but it is not valid.

Most everyday XML documents are only checked for well-formedness. Validation matters when two systems agree on a contract, such as an invoice format. The same split exists in JSON, where validating against a JSON Schema is a separate step from checking the syntax.

What formatting can change in the data

Pretty-printing XML (adding line breaks and indentation) can change the data. Section 2.10 of the specification says a parser "MUST always pass all characters in a document that are not markup through to the application". Whitespace between tags is part of the data, and it is up to the program reading the file to ignore it.

That matters for mixed content, where text and tags sit side by side:

<p>Total: <b>paid</b> in full</p>

If a formatter puts <b>paid</b> on its own indented line, the text now contains a line break and spaces it didn't have before. A data feed won't care. A document format that renders that text might show an extra gap. The spec provides an xml:space attribute for an element to signal that its white space should be kept, but whether a given tool honours it is up to that tool.

My take: pretty-print XML to read or debug it, then send the original bytes onward. Never ship the reformatted copy.

How to check XML in the browser

Every modern browser can parse XML with DOMParser, and it reports errors in an unusual way. According to MDN's parseFromString reference, malformed input does not throw. You get back a document that contains a <parsererror> element describing the problem:

const doc = new DOMParser().parseFromString(text, "application/xml");
const err = doc.querySelector("parsererror");
if (err) console.log("Not well-formed:", err.textContent);

If you skip that check, your code will happily walk a document that is really an error message. JSON fails the other way, throwing an exception like the one in Unexpected end of JSON input.

If you'd rather not write code, the XML viewer and formatter on this site indents, minifies and checks XML in the page; the tool code sends nothing you paste to a server.

Where you already use XML

Several formats you already use are XML underneath. MDN lists SVG, XHTML, MathML, RSS and RDF as XML-based.

Office documents are the surprising one. Microsoft's Open XML SDK documentation says "An Open XML file is stored in a ZIP archive for packaging and compression", and its parts are XML markup. Rename a .docx to .zip, open it, and you'll find files such as [Content_Types].xml and parts under word/.

On the web, the media type to use is application/xml. RFC 7303 keeps text/xml only as an alias, and XML-based types end in +xml, like image/svg+xml.

How XML compares to JSON

XML and JSON both describe nested data, but XML is the heavier format. XML has attributes, comments, namespaces and schemas built in, while JSON has typed values and fewer rules (see what the JSON format is). For new APIs and config files most teams now pick JSON or YAML, a choice covered in JSON vs YAML for config files.

XML's real limitation is verbosity. Every value is wrapped in a start and end tag, and all values are text until a schema or your code says otherwise. If you're starting fresh and don't need mixed text and markup, don't pick XML. If you're integrating with feeds, SOAP services, Office files or SVG, you'll be reading it anyway.

FAQ

What is an XML file used for?

Storing and exchanging structured data between programs: configuration files, data feeds like RSS, vector images (SVG) and the inside of Office documents such as .docx and .xlsx.

How do I open an XML file?

Any text editor opens it, because XML is plain text. A browser shows the raw tree, and an XML viewer or formatter adds indentation and syntax checking.

What is the difference between XML and HTML?

HTML has a fixed set of tags that describe how a page looks. XML has no predefined tags: you name your own to describe what the data is, and the syntax rules are strict.

Does an XML file need the declaration?

It is recommended but not required. The spec says documents SHOULD begin with one, and when it is there it must come first.

What is the difference between well-formed and valid XML?

Well-formed means the file follows XML's syntax rules. Valid means it is well-formed and also matches a DTD or XML Schema that says which elements and attributes are allowed.

Sources