How to Format and Validate XML

How to Format and Validate XML

Formatting XML feels like formatting JSON: press a button, get indentation, nothing changes. That is almost true, and the exception is the reason it is worth being careful.

Our XML formatter pretty-prints, minifies, validates and shows a collapsible tree, all locally.

Where XML differs from JSON

In JSON, whitespace between tokens is insignificant. In XML, whitespace inside an element is text content.

<name>Ada Lovelace</name>

Add a newline and indentation, and you have changed the value:

<name>
  Ada Lovelace
</name>

Applications that trim their input will not care. Applications that compare strings exactly will. That is why a formatter must know when it is safe to break a line — which brings us to mixed content.

Mixed content: the part formatters get wrong

An element with text and child elements is “mixed content”:

<p>Hello <b>world</b> tail</p>

A naive formatter puts each child on its own line, injecting whitespace into text that is supposed to read “Hello world tail”. A careful formatter leaves mixed-content subtrees on one line, which is what ours does.

Pure-element structures — the usual case for config and data files — format normally, with 2 or 4 spaces or tabs.

The errors that actually break documents

  • Unclosed and mismatched tags. <a><b></a> is the classic; the error message usually points at the line where the parser gave up, which is often one line after the real mistake.
  • Unescaped & and <. A bare & must be &amp; and a stray < must be &lt; — unless it starts a tag.
  • Case sensitivity. <Item> and <item> are different elements. Closing with the wrong case is an error, not a warning.
  • Duplicate attributes. <a id="1" id="2"> is invalid; the parser will stop.

The formatter reports the line and column of the first error, and refuses to produce output — which matters, because a half-formatted document is more dangerous than none.

Things worth preserving that formatters often drop

The XML declaration (<?xml version="1.0"?>), the DOCTYPE, comments and processing instructions are all part of the document. A formatter that silently deletes them has changed your file, not just its whitespace.

When to minify instead

Minifying removes the indentation and collapses whitespace between elements. It is worth it for large documents shipped over the wire, and pointless for a config file you read by hand. Toggle it when the file is machine input, not human input.