Reading XML that arrived as one line
XML from an API, a SOAP envelope, an RSS feed or a build artefact usually comes with every line break stripped. The structure is all still there, just invisible. Re-indenting it makes the nesting legible again, which is normally the whole reason you opened the file.
The parts that must not be touched
Formatting XML looks like a whitespace problem and is really a parsing problem. Three regions carry meaning that reindenting would destroy:
- Attribute values —
<a title="x > y">contains a>that does not end the tag. - CDATA sections — everything between
<![CDATA[and]]>is literal, including markup and spacing. - xml:space="preserve" — an explicit instruction that whitespace inside this element is content, not layout.
This tool tokenises the document before touching it, so all three survive. A formatter built on regular expressions typically mangles at least one.
Mixed content and minification
Minifying removes whitespace between tags, but not whitespace beside text. In <p>Hello <b>there</b></p> that space is part of the sentence; deleting it would render “Hellothere”. Distinguishing the two cases is the difference between a minifier you can trust on documents and one that only works on machine-generated data.
To turn XML into JSON, use XML to JSON, and for the reverse JSON to XML. For a sitemap specifically the XML sitemap generator produces the exact format search engines expect. For HTML rather than XML, use the HTML beautifier.