How to Format and Check XML

Learn the rules of well-formed XML, how to pretty-print and minify it, and how to find the common mistakes: unclosed tags, bad nesting and unescaped characters.

XML that comes out of an API or a config generator is often a single unreadable line. Formatting makes the structure visible, and checking that it is well formed catches the errors that stop parsers.

What well-formed means

Well-formed XML has exactly one root element, every opening tag has a matching closing tag in the right order, attribute values are quoted, and tag names are case sensitive. A parser stops at the first violation, so one mistake makes the whole document unusable.

Well-formed is not the same as valid. Validity means the document also follows a schema (XSD or DTD), which needs a validator that knows the schema.

Pretty-printing and minifying

Pretty-printing puts each element on its own line and indents by depth, which is what you want for reading and for diffs in version control. Minifying removes the whitespace between tags to save bytes. Both keep the data the same, but be careful with mixed content, where whitespace inside text can matter.

Common mistakes

Unclosed or mismatched tags are the most frequent error, usually after hand editing. Next come unescaped special characters: write & for an ampersand and < for a less-than sign in text, or wrap raw text in a CDATA section. Whitespace before the XML declaration also breaks strict parsers.

XML and other formats

XML is still common in configuration files, feeds, SOAP services and office documents. If you receive XML but your code works with JSON, convert it with a library rather than by hand, and format the result with a JSON formatter to check it.

Related tools

All guides