XML Formatter

Format, beautify, and validate XML online with syntax highlighting. Paste minified XML and get clean indented output instantly.

XML formatting takes raw or minified XML and rewrites it with consistent indentation, line breaks, and optional attribute sorting so it is readable by humans. This tool runs the parse, validation, and pretty-print steps entirely in your browser using the native DOMParser API. Paste any well-formed XML 1.0 document and get back a syntax-highlighted output with line numbers, attribute alignment, and an element count. Invalid XML produces an error message with the offending line number.

Ad
Ad

About XML Formatter

How XML Formatting Works

XML formatting walks the document tree and emits each opening tag, text node, and closing tag on its own line with one indent level per nesting depth. The W3C XML 1.0 specification defines a parser as "well-formedness-checking", so any conforming parser - including the browser's DOMParser - rejects mismatched tags, missing quotes around attribute values, and unescaped ampersands. This tool first parses the input, surfaces any error, then pretty-prints the valid tree using a small custom tokenizer rather than re-serialising via XMLSerializer (which strips comments and collapses CDATA in some browsers).

Worked example: The minified input <bookstore><book id="1"><title>The Hobbit</title></book></bookstore> becomes:

<bookstore>
  <book id="1">
    <title>The Hobbit</title>
  </book>
</bookstore>

Notice that the leaf element <title>The Hobbit</title> stays on one line - keeping short text content inline reduces visual noise and matches the convention used by Visual Studio Code, IntelliJ, and xmllint. The formatter also preserves comments, CDATA sections, processing instructions like <?xml version="1.0"?>, and doctype declarations exactly as written.

Why Format XML in 2026?

XML is still everywhere in enterprise systems even though JSON dominates new web APIs. JSON has become the primary format for most new public APIs over the last decade, but XML remains the dominant choice for SOAP services, SAML 2.0 single sign-on, RSS and Atom feeds, Office Open XML (.docx, .xlsx), SVG, EPUB, financial messaging via ISO 20022 and FIX, and government data exchange formats. Banks, insurance carriers, healthcare systems running HL7v3, and the entire SOAP middleware ecosystem still talk in XML, so anyone working in those domains needs a fast way to read minified payloads.

Common situations that call for an XML formatter:

ScenarioWhy You Need Formatting
SOAP API responseServers return a single long line. Formatting reveals the envelope, header, body, and fault structure.
SAML assertion debuggingIdentity providers emit base64-encoded XML. Decode then format to inspect attribute statements and conditions.
Office Open XML inspectionThe XML inside a .docx is minified. Formatting exposes the document.xml and styles.xml structure.
SVG editingDesigners export single-line SVG. Formatting makes path data, group transforms, and gradients editable by hand.
RSS or Atom feed diagnosisAggregators reject malformed feeds. Validating then formatting pinpoints the broken item.
Configuration filesSpring, Maven, Tomcat, and Log4j XML configs need clean diffs in version control.

For converting XML to other formats, the XML to JSON Converter handles the structural mapping. If you have JSON instead, the JSON Formatter does the same pretty-print and validate workflow.

What Makes XML Well-Formed vs Valid?

Well-formed XML obeys the syntactic rules of the XML 1.0 specification - one root element, properly nested tags, quoted attribute values, escaped special characters. Valid XML is well-formed and also conforms to a schema (DTD, XSD, or RELAX NG) that defines which elements and attributes are allowed where. This tool checks well-formedness, which is what 95% of debugging scenarios need. Schema validation requires the schema document and is usually done in code via Xerces, libxml2, or .NET XmlReader.

The five well-formedness rules every XML document must follow, per the W3C specification:

RuleExample of Violation
Exactly one root elementTwo sibling elements at the top level with no parent
Every opening tag has a matching closing tag<p>Hello with no </p>
Tags must be properly nested<b><i>text</b></i> (overlapping)
Attribute values must be quoted<img src=photo.jpg> (no quotes)
Special characters must be escapedLiteral &, <, or > in text content

The browser's DOMParser implements these rules natively. When it encounters a violation it returns a document whose root element is parsererror instead of your intended root, and the parser error description is in the text content. This tool extracts that description and the line number when one is present.

XML vs JSON: When Should You Pick Which?

JSON wins on size, parse speed, and JavaScript-native handling. XML wins on schema validation, mixed content, namespaces, comments, and document-oriented data. The decision usually comes down to ecosystem rather than technical merit.

FeatureXMLJSON
CommentsYes - <!-- ... -->No (JSONC is non-standard)
Attributes vs elementsBoth, distinguishableEverything is a key-value pair
Schema validationXSD, DTD, RELAX NG - mature toolingJSON Schema - newer, less ubiquitous
NamespacesFirst-class supportNo native concept
Mixed contentYes (text and elements interleaved)Not natively
Typical size3-4x larger than JSON for the same dataSmaller
Parse speed2-5x slower than JSON in most languagesFaster
Mainstream use in 2026Enterprise, SOAP, SAML, Office formats, RSS, SVG, financial messagingREST APIs, config (npm, Composer), NoSQL

If you are starting a new public API or microservice, JSON is the default choice. If you are working with SAML SSO, processing .docx files, parsing an Atom feed, or integrating with an established SOAP service, XML is non-negotiable. The two formats coexist - many systems accept both and use the Accept header to choose.

Common XML Mistakes and How to Spot Them

Most XML errors come from a small set of recurring mistakes. The DOMParser error messages are sometimes terse, so it helps to know the patterns.

Unclosed tags. The single most common error. The parser usually reports "expected end of tag" at the line where the next element starts. Look up the tree from that line to find the tag that never closed.

Unescaped ampersands in attribute values or text. Writing <url href="https://example.com/?a=1&b=2"/> instead of &amp; breaks the parser. The five characters that must be escaped in XML are & (&amp;), < (&lt;), > (&gt; - only required in CDATA contexts), " (&quot; - inside attribute values), and ' (&apos; - inside attribute values).

Case-sensitivity errors. Unlike HTML, XML is case-sensitive: <Item> and <item> are different elements. A closing tag with different casing throws a mismatch error.

Missing XML declaration encoding. If the file is saved as UTF-16 but the declaration says <?xml version="1.0" encoding="UTF-8"?>, parsers reject it. Match the declaration to the actual file encoding, or omit the encoding attribute to let the parser auto-detect.

Namespace prefix without binding. Using <soap:Envelope> without declaring xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" on an ancestor element produces an "unbound namespace prefix" error.

Invalid characters. XML 1.0 disallows most control characters in the 0x00-0x1F range except tab, newline, and carriage return. Copying text from a Windows source with embedded NULL bytes or vertical tabs trips this. The error usually says "invalid character reference".

What About Namespaces?

XML namespaces let documents combine vocabularies without name collisions. They are declared with xmlns:prefix="URI" on an element and apply to that element and all descendants. The URI is an identifier, not a fetchable location - it never has to resolve. This tool preserves namespace declarations exactly as written and never expands prefixes.

Common NamespaceURIWhere You See It
SOAP Envelopehttp://schemas.xmlsoap.org/soap/envelope/All SOAP 1.1 messages
SOAP 1.2http://www.w3.org/2003/05/soap-envelopeModern SOAP services
SAML 2.0urn:oasis:names:tc:SAML:2.0:assertionIdentity provider assertions
XML Schema instancehttp://www.w3.org/2001/XMLSchema-instanceUsed for xsi:type and xsi:nil attributes
Atom feedhttp://www.w3.org/2005/AtomRSS/Atom syndication feeds
SVGhttp://www.w3.org/2000/svgScalable Vector Graphics
Office Open XMLhttp://schemas.openxmlformats.org/wordprocessingml/2006/main.docx body content

If you need to encode or decode XML that has been transported as base64 - common with SAML responses delivered in HTTP POST bindings - the Base64 Encoder/Decoder handles that step before you paste into this formatter.

Tips for Working With Large XML Documents

This tool caps input at 5 MB, which covers virtually all hand-edited and API-response XML. For larger documents - multi-megabyte exports from databases, full SBOM files, or industrial telemetry archives - a few practical strategies help:

Split before formatting. Most large XML is repetitive (many sibling records under one root). Extract one record, format it to understand the structure, then write a streaming script using SAX or StAX parsers to process the full file.

Use line-based tools for search. Even minified XML has tag boundaries. Running grep '<ElementName' across a 100 MB file is fast and tells you where to look. Once you find the element, copy that subtree into a formatter.

Switch to streaming parsers in code. DOM parsers load the entire document into memory and need roughly 5-10x the file size in RAM. Streaming parsers (SAX in Java, lxml.iterparse in Python, XMLReader in PHP, XmlReader in .NET) read sequentially and use constant memory regardless of file size.

Validate against a schema in batch. The xmllint command-line tool (libxml2) validates against XSD or DTD and emits all errors at once. Run xmllint --schema schema.xsd --noout file.xml for batch checking. For HTML documents, the HTML Prettifier handles HTML-specific quirks like void elements and self-closing tags.

How Major Languages Parse and Pretty-Print XML

Every mainstream language ships a built-in or de-facto-standard XML library, and the output format you see in this tool matches what those libraries produce by default. Knowing the language equivalents helps when you want to script the same transformation across a directory of files.

LanguageLibraryPretty-print Call
JavaScript (browser)DOMParser / XMLSerializernew XMLSerializer().serializeToString(doc) - whitespace must be re-added by hand, as in this tool
Pythonxml.etree.ElementTreeET.indent(tree, space=" ") then ET.tostring(root, encoding="unicode") (3.9+)
Python (alt)lxmletree.tostring(root, pretty_print=True, encoding="unicode")
Javajavax.xml.transformTransformerFactory with OutputKeys.INDENT set to "yes" and the indent-amount property set
C# / .NETSystem.Xml.Linq.XDocumentdoc.ToString() (formatted by default with 2-space indent)
Goencoding/xmlxml.MarshalIndent(v, "", " ")
PHPDOMDocument$dom->formatOutput = true; $dom->saveXML()
RubyREXMLREXML::Formatters::Pretty.new(2).write(doc, output)
Command linexmllint (libxml2)xmllint --format file.xml - bundled with macOS and most Linux distros

One subtle gotcha: many libraries ignore whitespace text nodes during parse but preserve them during serialise, which produces ugly nested indentation when you re-format an already-formatted file. Python's ElementTree fixed this in 3.9 with the dedicated ET.indent() helper; older versions need a manual recursive whitespace strip first. Browser XMLSerializer has the same problem - this tool sidesteps it by tokenising the raw string rather than round-tripping through the DOM.

For workflows that involve converting between XML and other formats, the YAML to JSON Converter handles config-format translation, and the XML to JSON Converter maps XML trees to equivalent JSON structures using the common Badgerfish or Parker conventions.

Privacy and How This Tool Runs

Every operation happens in your browser. The XML you paste is parsed by the browser's built-in DOMParser, formatted by JavaScript running on your device, and never sent to any server. There are no analytics on the input content, no logging, and no cloud parser. This matters for XML in particular because SAML assertions, SOAP envelopes, and business documents frequently contain personally identifiable information, credentials, or financial data that should not be uploaded to third-party services.

Because everything is client-side, the tool also works offline once the page has loaded. If your connection drops mid-task, the formatter, validator, and download functions all continue to work. The 5 MB cap exists to keep memory usage reasonable on lower-spec devices - parsing a multi-megabyte XML tree can consume hundreds of megabytes of JavaScript heap.

Sources

Frequently Asked Questions

How does this XML formatter validate my input?

It uses the browser's native DOMParser to parse the XML and check for syntax errors. If the parser returns a parsererror node, the tool extracts the error message and line number and shows it in a red panel. No data leaves your device.

What is the difference between Format, Minify, and Validate modes?

Format adds indentation and line breaks for readability. Minify strips whitespace between tags to produce the smallest possible output. Validate just checks the XML for well-formedness without changing it. All three modes report parse errors with line numbers.

Can I sort attributes alphabetically?

Yes. Toggle the Sort attributes option and every element's attributes will be reordered alphabetically by name. This is useful when diffing XML files where different tools emit attributes in different orders, since attribute order is not semantically meaningful in XML.

Does the formatter preserve comments and CDATA sections?

Yes. Comments, CDATA blocks, processing instructions, and doctype declarations are kept verbatim. CDATA content is never re-indented because the spec treats every character inside CDATA as literal text.

Is there a size limit on the input?

The tool caps input at 5 MB to keep the browser responsive. Most XML documents you encounter from APIs, configuration files, or SOAP responses sit well under that limit. For larger files use a desktop XML editor or a streaming parser instead.

Link to this tool

Copy this HTML to link to this tool from your website or blog.

<a href="https://toolboxkit.io/tools/xml-formatter/" title="XML Formatter - Free Online Tool">Try XML Formatter on ToolboxKit.io</a>