XML Formatter
The XML Formatter is a free browser-based tool that formats, validates, and converts XML documents without sending data to any server. It uses fast-xml-parser to parse and re-serialize XML with consistent indentation, reports well-formedness errors with exact line and column positions, and can convert XML to JSON in one click with attribute keys preserved as @_ prefixes.
XML Formatter & Beautifier
How it works
Last updated: November 2026XML (Extensible Markup Language) is a text-based format for storing and transporting structured data. Defined by the W3C, XML uses nested tags to represent hierarchical data — the same idea as HTML, but with custom tag names you define yourself.
This tool uses fast-xml-parser — a fast, DOM-free JavaScript library — to parse and reformat XML entirely in your browser. No data is ever sent to a server.
- Beautify — parses your XML and re-serializes it with consistent indentation. Also rewrites the input box so you always see clean XML.
- Minify — strips all whitespace between tags for the most compact representation. Output only — input is unchanged.
- Validate — checks for well-formedness errors and reports the exact line and column of the first error in the status bar.
- Convert → JSON — converts XML to a JSON object. Attributes appear as keys prefixed with
@_. Output only — input is unchanged.
XML Quick Reference
| Construct | Syntax | Example |
|---|---|---|
| Element | <tag>content</tag> | <name>Alice</name> |
| Self-closing | <tag /> | <br /> |
| Attribute | name="value" | <user id="1"> |
| Comment | <!-- text --> | <!-- metadata --> |
| Declaration | <?xml version="1.0"?> | <?xml version="1.0" encoding="UTF-8"?> |
| CDATA | <![CDATA[...]]> | <![CDATA[<b>bold</b>]]> |
| Entity | & < > | <script> |
XML vs JSON at a Glance
| Feature | XML | JSON |
|---|---|---|
| Syntax | Tags + attributes | Objects + arrays |
| Comments | Yes <!-- --> | No |
| Attributes | Yes | No (use keys) |
| Namespaces | Yes | No |
| Schema | XSD, DTD | JSON Schema |
| Human-readable | Verbose | Concise |
| Primarily used for | Config, SOAP, RSS, office formats | REST APIs, web data |
Tips & Tricks
Validate before transforming
Beautify runs validation first — a green status bar means your XML is well-formed and safe to process downstream.
Use Convert → JSON for REST APIs
Many REST APIs accept JSON but receive XML from legacy systems. Convert in one click and paste directly into your API request body.
Load live XML feeds
Use the URL button to load RSS, Atom, or SOAP responses directly from a URL. The tool retries with a CORS proxy if the direct request is blocked.
Minify for storage or transport
Minified XML can be 30–50% smaller than its formatted equivalent for documents with many short values. Use Minify before storing in a database or sending over a network.
Self-closing tags are equivalent
<tag/> and <tag></tag> are identical in well-formed XML. The formatter preserves self-closing tags as-is.
Check entity encoding
Characters < > & ' " must be escaped as < > & ' " in element content and attribute values. Unescaped & is the most common XML parse error.
Code Examples
Node.js — fast-xml-parser
const { XMLParser, XMLBuilder } = require('fast-xml-parser');
const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_' });
const builder = new XMLBuilder({ ignoreAttributes: false, attributeNamePrefix: '@_', format: true, indentBy: ' ' });
const xml = `Alice `;
const parsed = parser.parse(xml);
const formatted = builder.build(parsed);
console.log(formatted); Python — xml.dom.minidom & ElementTree
import xml.dom.minidom import xml.etree.ElementTree as ET # Pretty-print XML raw = '' dom = xml.dom.minidom.parseString(raw) print(dom.toprettyxml(indent=' ')) # Parse XML into a tree tree = ET.parse('config.xml') root = tree.getroot() for child in root: print(child.tag, child.attrib) Alice
CLI — xmllint
# Format XML with xmllint (install: brew install libxml2)
xmllint --format file.xml
# Validate XML against a schema
xmllint --schema schema.xsd file.xml
# Format and save
xmllint --format file.xml -o formatted.xml
# Convert XML to JSON with python
python3 -c "import sys,json,xml.etree.ElementTree as ET; \
t=ET.parse(sys.argv[1]); print(json.dumps({t.getroot().tag:{}}))" file.xml
# Better: use xmltodict for a full conversion (pip install xmltodict)
python3 -c "import xmltodict,json,sys; print(json.dumps(xmltodict.parse(open(sys.argv[1]).read()), indent=2))" file.xml Frequently Asked Questions
- What does XML stand for?
- XML stands for Extensible Markup Language. It is a text-based format for storing and transporting structured data, defined by the W3C in the XML 1.0 specification (first published in 1998). Unlike HTML, XML has no predefined tags — you define your own tag names to describe your data, which is why it is called "extensible." XML is used in configuration files (Maven's pom.xml, Android's AndroidManifest.xml), APIs (SOAP web services, RSS and Atom feeds), office document formats (DOCX, XLSX, and PPTX are ZIP archives of XML files), and legacy enterprise data interchange via EDI and similar protocols. While JSON has replaced XML for most REST APIs, XML remains dominant in Java enterprise ecosystems, Microsoft-based tooling, publishing workflows (DITA, DocBook), and SVG vector graphics.
- What is an XML formatter?
- An XML formatter (also called an XML beautifier or XML pretty printer) takes compact or minified XML and adds indentation and line breaks so the structure is human-readable. It parses the XML into a tree, then serializes it back with consistent indentation. A formatter also validates the XML — if the input is not well-formed, it reports the exact line and column of the first error. This formatter uses fast-xml-parser, a DOM-free JavaScript library, which means it processes even large XML documents efficiently in the browser without building a full W3C DOM tree. For programmatic formatting, Node.js developers can use fast-xml-parser's XMLParser and XMLBuilder classes. Python's xml.dom.minidom module provides toprettyxml(indent=' ') for pretty-printing. To check well-formedness without reformatting, use the standalone XML Validator. To convert to JSON, use the built-in XML to JSON converter.
- Is my XML data sent to a server?
- No. All formatting, validation, and conversion runs entirely in your browser using JavaScript. Your data never leaves your machine and no account or sign-up is required. This is important for XML documents that may contain sensitive data — SOAP payloads with authentication tokens, Android manifests with API keys, Maven POM files with repository credentials, or enterprise data interchange files with business-critical content. The fast-xml-parser library runs entirely client-side; there are no server requests made when you format, validate, or convert XML. You can verify this by opening your browser's Network tab and confirming no requests are made when processing your document. The only time a network request is made is when you use the Load from URL feature to fetch a remote XML file.
- What is the difference between well-formed and valid XML?
- Well-formed XML follows the basic XML syntax rules: every opening tag has a matching closing tag, attributes are quoted, tags are properly nested (not interleaved), and there is exactly one root element. Well-formedness is a binary check — a document is either well-formed or it is not, and a non-well-formed document cannot be processed at all. Valid XML additionally conforms to a schema (DTD or XSD) that defines which elements and attributes are allowed, their order, data types, and cardinality. For example, a well-formed document might have a
element, but a valid document requires that phone contains only digits and has a specific format defined by the XSD. This formatter checks for well-formedness only — schema validation requires a dedicated XSD validator such as xmllint or the lxml library in Python. - What are the most common XML errors?
- The most common XML errors are: unclosed tags (every opening tag needs a closing tag or self-closing form such as
<br />), mismatched tag names (<Item>closed by</item>fails because XML is case-sensitive), unquoted attribute values (id=1must beid="1"), special characters not escaped as entities (unescaped&in content is the single most frequent error), and multiple root elements (XML requires exactly one root element wrapping all others). The formatter reports the exact line and column of the first error it encounters. The XML Validator focuses specifically on error detection with detailed fix suggestions without reformatting your document. - How do I convert XML to JSON?
- Use the Convert → JSON button. XML attributes are included in the JSON output prefixed with
@_(e.g.<user id="1">becomes{"user": {"@_id": "1"}}). Text content of an element appears as the#textkey when the element also has attributes or child elements. Note that XML's ordered elements and repeated sibling tags do not map cleanly to JSON objects — when multiple child elements share the same tag name (such as multiple<item>elements), fast-xml-parser converts them to a JSON array. Review the output carefully for such cases. For more complex conversions, the Python xmltodict library or Node.js's xml2js package offer additional control over how attributes and text nodes are mapped. See the dedicated XML to JSON tool for a focused conversion workflow. - What is the difference between XML and HTML?
- HTML is a specific application of markup designed for web pages with fixed tags (
div,p,img, etc.) and a forgiving parser that handles unclosed tags and other errors gracefully — browsers still render a page even with broken markup. XML is a general-purpose meta-language where you define your own tags, and the parser is strict — any single syntax error immediately stops processing and raises a fatal error. XHTML is HTML reformulated as strict XML syntax, requiring all tags to be properly closed. Modern web development uses HTML5 (not XML-based), which has its own HTML5 parsing rules separate from XML. While both XML and HTML use angle-bracket tag syntax, they serve entirely different purposes — XML is for structured data storage and interchange, HTML is for hypertext document rendering. SVG and MathML are XML-based formats that can be embedded inside HTML5 documents. - What are XML namespaces?
- XML namespaces prevent tag name collisions when combining XML from different sources into a single document. A namespace is declared with the
xmlnsattribute and an arbitrary prefix:<root xmlns:app="https://example.com/app">. Tags in that namespace use the prefix:<app:user>. The namespace URI is just a unique identifier — it does not need to point to any real URL. The default namespace (without a prefix) is declared asxmlns="https://..."and applies to all unprefixed tags within the element. Namespaces are pervasive in SOAP web services, SVG, MathML, and Office Open XML (DOCX, XLSX) formats. The formatter preserves all namespace declarations in the output exactly as they appear in the input. - How do I minify XML?
- Click the Minify button to remove all whitespace between tags and produce the most compact valid XML. In Node.js, use fast-xml-parser's
XMLBuilderwithformat: false. In Python, usexml.etree.ElementTreeto parse and re-serialize without pretty-printing:ET.tostring(tree.getroot(), encoding='unicode')produces compact XML. Minified XML reduces file size for network transfer and storage. XML with consistent indentation often includes substantial whitespace — a 100 KB formatted XML document may shrink to 60 KB when minified. Additionally enabling gzip or Brotli compression gives a further 70-80% reduction because XML's repetitive tag structure compresses extremely well. Keep the formatted version in source control for readability; use minified XML only in production transmission and storage. - What is CDATA in XML?
- CDATA (Character Data) sections let you include text containing XML special characters without escaping them. A CDATA section looks like
<![CDATA[ raw content here ]]>. Everything inside is treated as literal text, not markup — the XML parser ignores all angle brackets, ampersands, and other special characters within the CDATA block. CDATA sections end at the first occurrence of]]>, so that sequence cannot appear inside a CDATA section (you must split it into two adjacent CDATA sections if needed). CDATA is commonly used to embed HTML snippets in RSS feeds, SQL queries in Spring XML configuration, or JavaScript in XHTML documents. The formatter preserves CDATA sections in the output exactly as they appear in the input, including their content verbatim. - What is the XML declaration?
- The XML declaration is an optional first line:
<?xml version="1.0" encoding="UTF-8"?>. It specifies the XML version (always 1.0 in practice — XML 1.1 exists but is rarely used) and the character encoding of the document. If omitted, parsers assume UTF-8 for documents without a byte-order mark. The standalone="yes" attribute can optionally indicate that the document does not depend on an external DTD. The declaration must appear as the very first content of the file — no whitespace or BOM preceding it. It is strongly recommended for documents that may be transmitted between systems with different platform encoding defaults, such as Windows (often UTF-16) and Unix systems. Including the encoding declaration prevents silent data corruption when documents contain non-ASCII characters like accented letters, CJK characters, or emoji. - What is XPath and how is it used?
- XPath is a query language for selecting nodes in an XML document, defined by the W3C. It uses path expressions like
/root/users/user[@id='1']/nameto navigate the tree hierarchically. XPath supports predicates (filter conditions in square brackets), axes (parent::, ancestor::, following-sibling::), and functions (contains(), starts-with(), count()). The current standard is XPath 3.1. XPath is used in XSLT transformations, Selenium and Playwright web testing (locating elements in the DOM), and XML processing in Python wherexml.etree.ElementTreesupports a limited XPath subset and lxml supports the full XPath 1.0 specification. XSLT uses XPath expressions to define template matching rules and select nodes for transformation. For querying JSON in a similar way, see the JSONPath Playground. - What is the difference between DTD and XSD?
- DTD (Document Type Definition) and XSD (XML Schema Definition, also called XML Schema) are both ways to define the allowed structure of an XML document. A DTD is written in a compact non-XML syntax, supports basic element and attribute declarations, but cannot constrain data types — it cannot enforce that an element must contain an integer, a date, or a string matching a specific pattern. XSD is written in XML itself, supports rich data types (xs:integer, xs:date, xs:string, regular expression patterns, min/max occurrence constraints), namespace awareness, and type inheritance. For modern XML-based APIs and enterprise data exchange (SOAP, WSDL, Office Open XML, insurance and financial EDI standards), XSD is the standard. DTDs appear mainly in older systems, the HTML 4 DOCTYPE declaration (), and XHTML document type declarations. RELAX NG is an alternative schema language that is simpler than XSD and also widely used.
- What is XSLT?
- XSLT (Extensible Stylesheet Language Transformations) is a language for transforming XML documents into other formats — another XML structure, HTML, plain text, or JSON. An XSLT stylesheet is itself an XML document that defines templates (
xsl:template) that match XML nodes using XPath expressions and specifies how to render matched content in the output. XSLT is used in content management systems, technical documentation publishing pipelines (DocBook to PDF or HTML), and legacy enterprise integrations where XML is the canonical data format. The W3C XSLT 3.0 specification (2017) added higher-order functions, streaming for large documents, and JSON support via json-to-xml() and xml-to-json() functions. In Java, the javax.xml.transform API provides XSLT processing. Modern alternatives for simpler XML-to-JSON transforms include fast-xml-parser (Node.js) and lxml with the objectify API (Python). - How do I handle special characters in XML?
- XML has five predefined entity references:
&for&,<for<,>for>,'for', and"for". These must be used whenever the literal character appears in element content or attribute values. For arbitrary Unicode characters, use numeric character references:©(decimal) or©(hex) for the copyright symbol. To avoid escaping large blocks of text, wrap content in a CDATA section. The>entity is technically only required inside CDATA sections or when it appears as the sequence]]>, but it is considered good practice to escape all five characters. In Python, xml.etree.ElementTree escapes all five automatically when you use ET.tostring(). Unescaped&is by far the most common XML parse error. - How do I validate XML against an XSD schema?
- Browser-based tools — including this formatter — check well-formedness only, not schema validity. To validate against an XSD, use
xmllinton the command line:xmllint --schema schema.xsd document.xml --noout(install via brew install libxml2 on macOS). In Python, thelxmllibrary supports full XSD validation:schema = etree.XMLSchema(etree.parse('schema.xsd')); schema.validate(etree.parse('document.xml')). If validation fails, schema.error_log contains the full list of violations. In Java, usejavax.xml.validation.SchemaFactorywith the W3C_XML_SCHEMA_NS_URI constant. In .NET, XmlReader with XmlReaderSettings.Schemas handles XSD validation. Note that XSD validation reports all constraint violations, not just the first one — unlike well-formedness checking which stops at the first parse error.
Related Tools
Other free developer tools available on DevFormatter.
JSON Formatter
Format, validate, and minify JSON. Sort keys, find duplicates, and explore with Tree view.
YAML Formatter
Format, validate, and convert YAML. Detects YAML 1.1 coercion risks and expands anchors.
JSON Pretty Print
Instantly pretty-print and beautify compact or minified JSON with clean indentation.
XML to JSON
Convert XML to structured JSON. Attributes preserved as @_ keys, runs in your browser.
jq Playground
Run jq queries against JSON data instantly in your browser.
Base64 Encode / Decode
Encode text or binary data to Base64, or decode Base64 strings back to plain text.
URL Encode / Decode
Percent-encode URLs and query strings, or decode %XX sequences back to readable text.
XML Validator
Check XML well-formedness with exact line and column error positions and fix suggestions.