All articles

How to pretty print XML

· 3 min read

XML often arrives as one long line: SOAP responses, payment gateway callbacks, RSS feeds, sitemaps, Android resources and Maven files exported by tools. Pretty printing adds line breaks and indentation so you can see the structure. The catch is that in XML, whitespace can be part of the data, so a formatter must be careful about where it adds it.

On the command line

xmllint

xmllint comes with libxml2 and is preinstalled on macOS and many Linux distributions:

xmllint --format response.xml
curl -s https://example.com/sitemap.xml | xmllint --format -

It checks well-formedness at the same time and prints errors with line numbers. Indentation is two spaces; set XMLLINT_INDENT to change it:

XMLLINT_INDENT='    ' xmllint --format response.xml

Other options

xmlstarlet fo response.xml          # xmlstarlet
yq -p=xml -o=xml '.' response.xml   # yq, if you already use it for YAML

In Python

ElementTree.indent (Python 3.9+) indents in place:

import xml.etree.ElementTree as ET

tree = ET.parse("response.xml")
ET.indent(tree, space="  ")
tree.write("formatted.xml", encoding="utf-8", xml_declaration=True)

minidom is older, but common in existing code:

from xml.dom import minidom
print(minidom.parseString(xml_text).toprettyxml(indent="  "))

toprettyxml adds blank lines when the input already contains whitespace between tags. Strip it first, or use ElementTree.indent.

For untrusted XML, use defusedxml instead of the standard parsers; it blocks entity expansion and external entity attacks.

In JavaScript

Browsers can parse XML with DOMParser, which also tells you whether it's well-formed:

function parseXml(text) {
  const doc = new DOMParser().parseFromString(text, "application/xml");
  const error = doc.querySelector("parsererror");
  if (error) throw new Error(error.textContent);
  return doc;
}

There's no built-in pretty printer, but a small recursive function covers data-oriented XML:

function formatXml(node, indent = "") {
  const pad = "  ";
  if (node.nodeType === Node.TEXT_NODE) return node.textContent.trim() ? indent + node.textContent.trim() : "";
  if (node.nodeType === Node.COMMENT_NODE) return `${indent}<!--${node.textContent}-->`;
  if (node.nodeType === Node.CDATA_SECTION_NODE) return `${indent}<![CDATA[${node.textContent}]]>`;

  const attrs = [...node.attributes].map((a) => ` ${a.name}="${a.value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;")}"`).join("");
  const children = [...node.childNodes];
  if (children.length === 0) return `${indent}<${node.nodeName}${attrs}/>`;
  if (children.length === 1 && children[0].nodeType === Node.TEXT_NODE) {
    const text = new XMLSerializer().serializeToString(children[0]);
    return `${indent}<${node.nodeName}${attrs}>${text}</${node.nodeName}>`;
  }
  const inner = children.map((c) => formatXml(c, indent + pad)).filter(Boolean).join("\n");
  return `${indent}<${node.nodeName}${attrs}>\n${inner}\n${indent}</${node.nodeName}>`;
}

formatXml(parseXml(xmlText).documentElement);

It trims text inside mixed content, so don't use it for documents where whitespace matters (see below). In Node.js, which has no DOMParser, libraries such as fast-xml-parser or xml-formatter do the job.

When whitespace is data

Whitespace between elements in a data document is insignificant to most consumers:

<order><id>42</id><total>9.99</total></order>

Adding line breaks between <id> and <total> is harmless. But in mixed content, where text and elements are interleaved, whitespace is part of the text:

<p>Press <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy.</p>

Putting each <kbd> on its own line changes the text to "Press \n Ctrl \n + ...". The same applies to elements with xml:space="preserve", to text formats like DocBook and XHTML, and to signed XML: XML Signature verification fails if formatting changes the signed content.

A careful formatter keeps mixed content on one line and leaves xml:space="preserve" elements untouched.

Other things to preserve

  • CDATA sections should stay as CDATA, not be converted to escaped text, if the consumer expects them.
  • The XML declaration (<?xml version="1.0" encoding="UTF-8"?>) must remain the very first thing in the file.
  • Encoding: if the declaration says ISO-8859-1, the file must be saved in that encoding, or the declaration updated.
  • Namespaces and prefixes must stay as written; some consumers compare prefixes even though they shouldn't.
  • Comments and processing instructions are often meaningful (build tools, IDE hints).

Common well-formedness errors

Error Cause
Mismatched tag <a><b></a></b>: tags closed in the wrong order
Unclosed element at end of input A missing closing tag
Unescaped & Write &amp; in text and attributes (common in URLs)
Unescaped < in text Write &lt; or wrap the text in CDATA
Content before the prolog A BOM, whitespace or log text before <?xml
Multiple root elements XML allows exactly one root

When you're choosing a format for new configuration or APIs rather than reading existing XML, YAML vs JSON compares the usual alternatives. For JSON, the equivalent of this guide is pretty printing with JSON.stringify.

Frequently asked questions

What's the difference between well-formed and valid XML?

Well-formed means the syntax is correct: one root element, properly nested and closed tags, quoted attributes. Valid means it also matches a schema (XSD, DTD or RELAX NG).

Does pretty printing change the meaning of XML?

It can. Added whitespace becomes part of text content in elements with mixed content or xml:space="preserve". For data-only XML it's usually safe.

Why does my XML fail with 'content is not allowed in prolog'?

Something comes before the <?xml ...?> declaration or root element, often a byte order mark, whitespace or text from a log line.

Should I minify XML for production?

For sitemaps and feeds, compression matters much more than whitespace. Minify when size is critical, like large API payloads without compression.

Further reading