XML Formatter & Validator
Understanding XML formatting and well-formedness
This XML formatter turns dense markup into readable, consistently indented XML. It can also minify a document, check whether the syntax is well-formed, identify the first parser error, and summarize the parsed structure. Everything runs in the browser tab. The XML is not sent to a server, so the tool is suitable for development samples, configuration files, API responses, RSS feeds, SVG documents, build metadata, and other locally handled data. Browser-local processing is useful when a document should not be pasted into an unknown remote service, although ordinary precautions still apply when working on a shared or managed device.
In XML terminology, well-formed has a precise meaning. A well-formed document has exactly one root element, properly nested elements, matching start and end tag names, unique attribute names within each tag, legal characters, correctly escaped reserved characters, and valid namespace-prefix use. A document can satisfy all those syntax rules while still containing incorrect business data. Schema validation is the separate process that checks rules such as required fields, element order, allowed values, and datatypes against a DTD, XSD, Relax NG schema, or Schematron rule set. This page performs the syntax-level well-formedness check, not schema validation.
The formatter parses the source into a document tree before writing it back out. That is safer than trying to interpret nested XML with regular expressions. It also permits conservative treatment of mixed content. For example, the space in <p><b>one</b> <i>two</i></p> may be meaningful text, so the formatter does not casually replace it with indentation. Subtrees marked with xml:space="preserve" are also protected from ordinary reflow.
XML is both a textual notation and a tree model. The textual view includes angle brackets, entity references, quotes, comments, processing instructions, and optional declarations. After a successful parse, applications generally work with nodes: a document node contains one document element, and that element can contain attributes, text, and child elements. Pretty printing changes the textual presentation of that tree. It does not intentionally change element names, attribute values, character data, namespace declarations, comments, or processing instructions.
This distinction explains why formatting should begin with parsing. A visual indentation pattern can be misleading when tags are mismatched, when a quoted attribute contains a closing angle bracket, or when CDATA includes characters that resemble markup. A real XML parser follows the grammar and knows which characters are data in the current context. If parsing fails, there is no dependable document tree to format, so this tool reports the error instead of guessing at the intended structure.
How to use the XML formatter, validator, and minifier
Paste a complete XML document into the input field, or use the sample button to load a representative document. A fragment is acceptable only when it still has a single enclosing root element. Choose two spaces, four spaces, or a tab as the indentation unit before formatting. The choice affects presentation, not XML meaning. Two spaces produce compact output that is convenient for deeply nested documents, while four spaces can make moderate nesting easier to scan. Tabs allow each reader’s editor to control the displayed width.
- Format XML parses the source and writes readable output with the selected indentation.
- Validate only checks well-formedness without producing a rewritten copy of the document.
- Minify removes layout whitespace between structural nodes while preserving text, CDATA, comments, and protected whitespace.
- Copy result copies either the transformed XML or an error report. Download creates a local
formatted.xmlfile.
If parsing fails, the result shows the browser’s message and, when available, a line number, column number, source line, and caret. The reported location is where the parser detected the contradiction. The original mistake may occur earlier—for example, an omitted closing tag can remain unnoticed until a later end tag no longer matches the open-element stack. After correcting the first error, run the validator again because XML parsers normally stop at the first well-formedness failure.
A practical debugging routine is to validate before making cosmetic edits. Read the first parser message, inspect the highlighted line, and then look backward for the opening construct it refers to. Check quotes, ampersands, comment delimiters, CDATA boundaries, namespace declarations, and the most recently opened elements. Fix one issue and parse again. The next run may reveal a separate error that was hidden by the first one.
After the document is accepted, compare the formatted result with the source using a text diff when the XML is important. Most differences should be indentation, line endings, or equivalent empty-element notation. Review mixed-content areas especially carefully because whitespace can be data there. For a machine-generated configuration file, also run the consuming application’s own tests; well-formed XML is necessary, but it is not proof that the application understands the values.
The XML grammar and indentation formulas
The XML 1.0 document production captures the single-root rule. A document consists of a prolog, one document element, and optional trailing miscellaneous content such as comments, processing instructions, or whitespace:
Because the production contains one element term, two sibling root elements are not legal. Text outside the root is also rejected, although surrounding whitespace, comments, and processing instructions may be permitted. Within the tree, every non-empty start tag must be paired with an end tag having the same qualified name:
XML matching is case-sensitive. An opening <Item> is not closed by </item>, even if a human reader regards the words as equivalent. Nesting must also be orderly. The sequence <a><b></a></b> overlaps and is invalid because the most recently opened element, b, must close before its parent a. This stack-like rule gives XML its unambiguous tree structure.
Formatting follows the parsed tree rather than counting spaces in the source. The document node starts at depth zero, and each child is one level deeper than its parent:
If the indentation unit contains k characters, a node placed on its own line receives a prefix whose character length is:
Deep documents therefore gain more formatting characters than shallow documents with the same number of elements. If P is the set of nodes placed on separate lines and L is the serialized content before those line prefixes are added, the formatted length follows:
Not every child is eligible for a new line. The formatter treats an element as breakable only when it has structural children and no CDATA or significant text child. Layout whitespace must already contain a line break before it can be discarded. The governing predicate is:
This conservative rule protects mixed content. An element containing words around inline child elements remains compact because adding line breaks would add text whitespace. A fully minified element-only tree can still be expanded because it has no intervening text nodes. Existing indentation can also be replaced because its whitespace contains line breaks and is recognized as layout.
Whitespace behavior is one of the most important differences between XML formatting and ordinary source-code indentation. In an element-only data model, line breaks between child elements often exist only for readability. In mixed content, the same line breaks become part of the text stream. A paragraph such as <p>Read <em>this</em> now.</p> contains meaningful text before and after the child element. Replacing those boundaries with indented lines can change the rendered sentence or the string value used by another program.
The xml:space attribute gives an author an explicit way to communicate whitespace intent. A value of preserve applies to the element and is inherited by descendants unless a descendant restores default. This formatter carries that mode through the parsed tree. It does not attempt to infer a schema’s whitespace facet or an application’s custom trimming rules, so downstream software may still normalize values according to its own specification.
Serialization must escape reserved characters. In character data, ampersands and less-than signs are escaped, and a greater-than sign is escaped when needed to avoid forming a CDATA closing delimiter:
Attribute values additionally require the delimiting quotation mark to be escaped. Tabs, carriage returns, and line feeds are emitted as character references because XML attribute-value normalization could otherwise turn them into ordinary spaces during the next parse. XML defines only five named entities: &, <, >, ", and '. HTML-only names such as are not predefined in XML unless a DTD declares them.
A bare ampersand is a frequent error because XML treats it as the beginning of an entity or character reference. Text such as Research & Development must be represented in source markup with an escaped ampersand. Numeric references can represent characters by decimal or hexadecimal code point, but the referenced character must still be legal for the XML version being parsed. Escaping a forbidden control character does not automatically make it valid.
The formatter visits every parsed node once. For an element with k child subtrees, the work can be expressed as:
The constant term covers writing the current node and its attributes. Overall processing is linear in the number of nodes plus the generated output length, although extreme depth increases indentation output and recursive call depth. To avoid attempting an unexpectedly large parse, this page rejects input above four million characters.
Namespaces, prefixes, and qualified XML names
XML namespaces let documents combine vocabularies without treating every repeated local name as the same concept. A default declaration such as xmlns="urn:example:orders" places unprefixed element names in that namespace. A prefixed declaration such as xmlns:meta="urn:example:metadata" binds the prefix meta so a name like meta:source can be expanded to a namespace name and local name. The prefix is a shorthand chosen by the document author; the namespace name is the identity that namespace-aware software normally compares.
Default namespaces apply to unprefixed element names, but they do not automatically apply to unprefixed attributes. This often surprises developers who inspect a document visually and assume every nearby name inherits the same namespace. An attribute named id normally has no namespace, even when its element belongs to a default namespace. A prefixed attribute, by contrast, uses the namespace bound to its prefix.
Every prefix used on an element or attribute must be declared in scope, except the reserved XML prefix with its predefined binding. A declaration can appear on the same element or on an ancestor. Descendants may rebind a prefix, which means the same written prefix can identify different namespaces in different subtrees. The metrics panel lists distinct declarations and the element where each one appears, helping reveal unexpected rebinding or a default namespace introduced too high in the tree.
Formatting does not attempt to rename prefixes, merge declarations, or choose a preferred namespace style. Those transformations can be semantically delicate because namespace declarations affect descendant names, XPath expressions may depend on explicit bindings supplied by the caller, and some applications preserve prefixes for signatures or human conventions. This tool writes the declarations and qualified node names exposed by the parsed document rather than redesigning the namespace map.
When an XPath or integration reports that an element is missing even though it is visibly present, inspect its namespace before changing the XML. An unprefixed XPath name in many libraries means “no namespace,” not “whatever default namespace appears in the document.” The appropriate fix may be to bind a query prefix to the document’s namespace and use that prefix in the XPath. Well-formedness validation cannot diagnose a logically incorrect query, but the namespace summary provides useful evidence.
Worked example: finding a mismatched XML tag
Suppose a catalogue contains <catalog><product><name>Mug</name><product></catalog>. The second <product> was intended to be </product>. The parser can accept the opening tag temporarily, but when it reaches </catalog>, the innermost open element is still product. The end-tag name therefore fails the element type match rule. The reported position may point to the closing catalogue tag even though the actual typo occurs earlier.
After changing the second product tag to an end tag, the document becomes well-formed. Formatting with two spaces places product one level under catalog, while name sits two levels down. The text-only element <name>Mug</name> remains on one line because breaking around its text would insert character data. If the same product start tag contained id="1" id="2", the parser would reject it again because one element cannot contain duplicate attribute names.
Now imagine that the name is Mugs & Cups in the source. The bare ampersand starts what the parser expects to be an entity reference, but the following text does not form a legal reference. Writing Mugs & Cups in XML source represents the intended ampersand character. After parsing, the text node contains the ordinary character, and serialization escapes it again so the output remains parseable.
A namespace variation illustrates a different class of issue. If the product contains <meta:rating>5</meta:rating> without an in-scope xmlns:meta declaration, the qualified name uses an undeclared prefix and the document is not namespace-well-formed. Adding an appropriate declaration resolves the syntax problem. Whether that namespace name is the one expected by the catalogue application remains a schema or business-rule question.
Common XML syntax failures and how to investigate them
Mismatched tags are only one source of parser errors. An attribute must have a value and that value must be quoted. Both single and double quotation marks are legal delimiters, but the selected delimiter cannot appear literally inside the value. An input such as <item status=open> is therefore invalid, while <item status="open"> is well-formed. If a value needs a literal double quotation mark while double quotes delimit it, use " or switch the surrounding delimiter to single quotes.
Comments begin with <!-- and end with -->. The text of an XML comment cannot contain a double hyphen. That means a decorative separator made of repeated hyphens can invalidate an otherwise ordinary document. Comments also cannot be nested merely by writing another opening delimiter inside an existing comment. When a parser points near the end of a long comment, search the comment body for a forbidden -- sequence.
CDATA sections are useful when text contains many less-than signs or ampersands that should not be interpreted as markup. Their content begins after <![CDATA[ and ends at the first ]]>. The closing sequence cannot occur directly in CDATA content. CDATA also does not create a separate data type in the application’s string value; it is an alternative source representation for character data, although the browser DOM can preserve a distinct CDATA node.
Processing instructions have a target followed by optional data and end with ?>. The target name xml, in any combination of uppercase and lowercase letters, is reserved. An XML declaration resembles a processing instruction but has special placement and syntax rules: if present, it belongs at the beginning of the document, apart from a possible byte-order mark in the original byte stream.
Duplicate attributes are invalid even when the two values happen to be identical. Namespace processing can also make attributes conflict through expanded names, depending on their prefixes and bindings. A parser handles those details more reliably than a visual search. The structure metrics count ordinary attributes separately from namespace declarations so that namespace bookkeeping does not inflate the application-attribute total.
Another subtle failure comes from copying HTML into XML. HTML parsers permit conventions that XML does not, including certain unquoted values, case-insensitive element handling in HTML documents, and many named character references. XML requires explicit closing or self-closing syntax for every element and recognizes only its five predefined named entities unless a DTD supplies more. Markup that a browser repairs as HTML can therefore be rejected correctly as XML.
Formatting, minification, and canonicalization are different operations
Pretty printing is a readability operation. It adds or replaces layout whitespace where the formatter judges that doing so will not alter significant text. Minification pursues the opposite presentation goal by removing layout whitespace between structural nodes. Neither operation is XML canonicalization. Canonical XML is a precisely standardized representation used in contexts such as digital signatures, and it has detailed rules for namespace declarations, attribute ordering, line endings, character references, and comments.
Do not use the output of a general formatter as a substitute for a canonicalization algorithm when verifying or generating a signature. Even semantically equivalent changes can invalidate a byte-sensitive signature. Likewise, formatting a signed XML document can break a signature if the signature’s transforms do not exclude the changed whitespace. Use the signing library and canonicalization method required by the relevant protocol.
Minification does not guarantee the smallest possible byte sequence. It preserves comments, processing instructions, CDATA boundaries, declaration text, attributes, and significant character data. More aggressive size reduction might remove comments, shorten prefixes, normalize CDATA into escaped text, or apply compression, but each step has different compatibility implications. For network transfer, ordinary HTTP compression usually saves more space than risky structural rewriting.
Equivalent XML spellings can still produce textual differences. An empty element can be written as <entry></entry> or <entry/>. Attribute order is not semantically significant under the XML information model, though human conventions and poorly designed consumers sometimes care about it. Entity references can be replaced by the characters they denote and then re-escaped during serialization. Review output according to XML semantics rather than expecting byte-for-byte preservation.
Interpreting XML results, metrics, and limitations
A successful formatting or minifying run means the browser parsed the document without finding a well-formedness error. The structure panel then reports the root name, element and attribute totals, significant text nodes, comments, CDATA sections, processing instructions, maximum nesting depth, declaration presence, and character-count change. Namespace declarations are listed separately because an unexpected default namespace or prefix binding commonly explains why an XPath query or consuming application cannot find an otherwise visible element.
Maximum depth describes the deepest element encountered during traversal. A high value is not automatically an error, but extreme nesting can make documents hard to review and can stress recursive processing in some software. Element, attribute, and text-node counts provide a quick reasonableness check. If a feed expected to contain hundreds of records reports only a handful of elements, the source may be truncated even though the remaining XML is well-formed.
The character-count difference is a presentation metric, not a compression ratio or semantic score. Formatted output often grows because line breaks and indentation are added. Minified output often shrinks when the source contains layout whitespace. A small or zero change may mean the source was already close to the selected style, or that mixed content and preservation rules prevented safe reflow.
The verdict does not prove that dates, prices, identifiers, or required elements are correct. It also does not apply an XSD or another schema. External entities are not fetched, which avoids turning the browser formatter into an external-entity resolver. A document that depends on an external subset may therefore require a dedicated schema-aware desktop or build tool.
Formatting preserves comments, processing instructions, CDATA, text content, namespace declarations, and an existing XML declaration. Empty elements may be serialized using the equivalent short form, so <a></a> can become <a/>. Attribute order is retained from the parsed DOM but has no XML-defined meaning. Browser DOM APIs do not expose a document type’s complete internal subset, so a document containing internal entity declarations should be validated rather than reformatted here. The input is already JavaScript text when it reaches the parser; an encoding declaration is preserved as markup but cannot reinterpret the original file bytes.
That encoding limitation matters when diagnosing corrupted characters. A browser textarea receives Unicode characters after the operating system, browser, or copying application has already decoded the original bytes. If a file declared UTF-8 but was actually saved in another encoding, replacement characters or mojibake may already be present before this tool sees it. Resolve byte-decoding problems in an editor or parser that opens the original file directly with a chosen encoding.
Document type declarations require particular care. The browser DOM exposes the public and system identifiers, but it does not provide a complete portable representation of an internal subset. Internal entity declarations can influence the text produced by parsing, so reserializing such a document without full DTD information may not reproduce the original source safely. Validate-only mode is the prudent choice for DTD-dependent documents unless a dedicated XML library is available.
This tool also does not evaluate security or trust. Well-formed markup can contain hostile URLs, misleading instructions, enormous text values, or application-specific payloads. Do not execute embedded code or send a transformed document to a production system merely because the syntax check succeeds. Apply the same authorization, content validation, size limits, and review procedures that the destination normally requires.
Using the XML checker in development and review workflows
During API development, paste a failing XML response and validate it before investigating higher-level mapping code. A syntax failure can explain why a client reports a generic deserialization error. Once the response is well-formed, format it and inspect the hierarchy, namespace bindings, and repeated records. Then validate it with the service’s schema or contract tests to check the rules this page intentionally does not enforce.
For configuration files, compare the root name and structure metrics with a known-good version. A sudden change in maximum depth may reveal a misplaced closing tag that still leaves the document well-formed but changes the hierarchy. A different namespace declaration can cause an application to treat familiar-looking elements as unrelated names. These observations are diagnostic clues rather than definitive validation results.
In code review, formatted XML can make additions and removals easier to see, but automated formatting should use a stable, agreed configuration. Different formatters make different choices about mixed content, empty elements, declarations, CDATA, and attributes. Avoid creating noisy commits that rewrite an entire document unless the team has chosen that style deliberately. A targeted validation run may be more appropriate when only correctness is in question.
For tests and fixtures, preserve the original source when exact lexical details matter. Some tests intentionally exercise entity references, quotation styles, CDATA sections, comments, or unusual whitespace. Parsing and serializing can replace those spellings with equivalent ones, defeating a lexical test even though the information content remains correct. Use the transformed output as a new artifact only when semantic XML equivalence is the goal.
Large documents deserve additional caution. The four-million-character cap helps prevent an accidental oversized paste from monopolizing the tab, but node count and nesting depth also affect processing cost. A compact document can contain many tiny elements, and a deeply nested document can stress recursion. For production-scale feeds, streaming parsers and command-line tools are generally more appropriate than a browser textarea.
Sources. The syntax rules, character escaping, attribute normalization, CDATA behavior, xml:space, and predefined entities come from the W3C Extensible Markup Language (XML) 1.0 (Fifth Edition) Recommendation. Namespace rules come from Namespaces in XML 1.0 (Third Edition). Browser parser-error behavior is defined by the WHATWG HTML Standard. See XML 1.0, Namespaces in XML, and the DOM parsing specification.
Common questions about this XML checker
Does the validator check an XSD or DTD?
No. It checks XML syntax and namespace well-formedness only. Use a schema-aware processor when you must enforce element order, required attributes, datatypes, identity constraints, or domain-specific rules. A schema-aware processor may also apply default values or report validity errors that a general XML parser cannot infer.
Will pretty printing change mixed content?
The formatter deliberately avoids reindenting elements containing significant text, CDATA, or plain-space separators between inline elements. It also honors xml:space="preserve". Layout whitespace between structural children may be replaced. Because only the application or schema can know every whitespace rule, compare important transformed files before deployment.
Why is an error sometimes reported after the real typo?
A parser reports where the syntax becomes impossible to continue. An unclosed element may remain plausible until a later end tag conflicts with the currently open element, so inspect both the reported location and the earlier tag named in the message. Correct the first issue and run the check again to uncover any later errors.
Can a legitimate element be named parsererror?
Yes. This page discovers the namespace used by the browser’s injected parser-error element and checks that namespace instead of rejecting every user-authored element whose local name happens to be parsererror.
Does minifying XML reduce network transfer size?
It can remove visible indentation and line breaks from element-only regions, but transport compression such as gzip or Brotli usually provides a larger reduction. Minification here preserves comments, CDATA, processing instructions, and significant text, so it is intentionally conservative rather than byte-minimal.
Why does the output use a self-closing element?
An element with no child nodes can be serialized as <item/> instead of <item></item>. The two forms represent the same empty XML element. This lexical change does not add or remove element content.
Is this formatter suitable for digitally signed XML?
Use caution. Any textual rewrite may invalidate a signature depending on its transforms and canonicalization method. Validate signed XML without reformatting, and use the protocol’s required canonical XML implementation for signature work.
