All articles
Formatters
24 min readBy Akash Bijwe

XML Formatting: Structure, Namespaces and Pretty-Printing

Learn how XML is structured, what makes it well-formed, how namespaces work, and how to pretty-print XML safely for debugging and review.

XML Formatting: Structure, Namespaces and Pretty-Printing

XML has a reputation as the older, heavier cousin of JSON, but it has not gone away. It still carries enterprise integrations, office documents, Android layouts, SVG graphics, RSS and Atom feeds, SOAP services, sitemaps and build configuration. If you work on any of these, you will read XML, and you will often meet it as one long unreadable line. This guide explains how XML is structured, what makes a document well-formed, how namespaces work, and how to pretty-print XML so it can be read, reviewed and debugged.

What is XML?

XML, the Extensible Markup Language, is a text format for representing structured data as a tree of named elements. It is defined by the W3C in the XML 1.0 specification, and it was designed to be both human-readable and machine-readable, with a strict grammar so that every parser behaves the same way.

The word "extensible" matters. Unlike HTML, which has a fixed set of tags, XML lets you invent your own vocabulary. A bookstore, a payroll system and a vector graphic can all use XML, each with different element names. The MDN XML introduction gives a gentle overview.

A small document looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<library>
  <book id="b1" available="true">
    <title>Learning XML</title>
    <author>Ada Lovelace</author>
    <price currency="USD">29.99</price>
  </book>
</library>

The building blocks

XML has a small set of constructs. Knowing each one makes any document easier to read.

  • XML declaration. The optional first line, <?xml version="1.0" encoding="UTF-8"?>, states the version and character encoding. If present, it must be the very first thing in the file.
  • Elements. The main unit, written as a start tag, content and an end tag: <title>Learning XML</title>. An empty element can be written as <br/>.
  • Attributes. Name and value pairs inside the start tag, such as id="b1". Values must always be quoted.
  • Text content. Character data between tags.
  • Comments. Written <!-- like this -->.
  • CDATA sections. Blocks written <![CDATA[ ... ]]> in which characters such as < and & are treated literally.
  • Processing instructions. Directives for applications, such as a stylesheet link.
  • Entity references. Five predefined escapes: &lt;, &gt;, &amp;, &quot; and &apos;.

Well-formed versus valid

Two terms are often mixed up.

A document is well-formed when it obeys XML's syntax rules. A parser must reject a document that is not well-formed, and that is the key difference from HTML, which browsers repair silently. The rules are:

  1. There is exactly one root element.
  2. Every start tag has a matching end tag, or is self-closing.
  3. Elements are properly nested: <a><b></b></a>, never <a><b></a></b>.
  4. Attribute values are quoted, and an attribute name appears only once per element.
  5. Names are case-sensitive: <Item> and <item> are different.
  6. Special characters in text and attributes are escaped.

A document is valid when it is well-formed and also conforms to a schema that describes the allowed elements, order and types. Schemas can be written as a DTD, XML Schema (XSD), or RELAX NG. Well-formedness is about syntax. Validity is about meaning.

Why XML formatting matters

Whitespace between elements is usually insignificant, so these two documents describe the same data:

<order id="1"><item sku="A1" qty="2"/><item sku="B7" qty="1"/></order>
<order id="1">
  <item sku="A1" qty="2"/>
  <item sku="B7" qty="1"/>
</order>

People care about the difference:

  • Readability. Nested structure is obvious when each level is indented.
  • Debugging. SOAP responses, feed output and log payloads often arrive as a single line. Pretty-printing is the first step to finding the field that is wrong.
  • Diffs and reviews. One element per line means a version-control diff shows exactly what changed.
  • Spotting errors. Mismatched tags and misplaced attributes stand out in a regular layout.

A caution about whitespace

XML does not always ignore whitespace. In mixed content, where text and elements are interleaved, spaces can be part of the data:

<p>This is <b>important</b> text.</p>

If a formatter breaks that line after <b>, it can add or remove a visible space. Pretty-printing is safe for data-oriented XML (records, configuration, feeds). Treat it with care for document-oriented XML (prose with inline markup). Some formats also define their own whitespace rules, controlled by the xml:space attribute.

Namespaces

Namespaces solve a naming problem: what happens when two vocabularies use the same element name? A <title> in a book is not the same as a <title> in an HTML page. The Namespaces in XML recommendation lets each name belong to a vocabulary identified by a URI.

<feed xmlns="http://www.w3.org/2005/Atom"
      xmlns:media="http://search.yahoo.com/mrss/">
  <title>Example Feed</title>
  <entry>
    <title>First post</title>
    <media:thumbnail url="https://example.com/a.jpg"/>
  </entry>
</feed>

Key points:

  • xmlns="..." sets the default namespace for the element and its descendants.
  • xmlns:media="..." declares a prefix, used as media:thumbnail.
  • The URI is an identifier, not a link. It does not need to resolve to a web page.
  • The prefix is only a local alias. Two documents can use different prefixes for the same namespace and still mean the same thing.

Namespaces are the most common source of confusion when querying XML. An XPath expression such as //title finds nothing in the feed above unless you register the namespace and use a prefix in the query.

Real-world places you will meet XML

  • Web feeds: RSS and Atom.
  • Graphics: SVG is an XML vocabulary.
  • Sitemaps: the sitemap.xml that search engines read.
  • Office files: .docx, .xlsx and .pptx are zipped bundles of XML parts.
  • Android: layouts, manifests and resources.
  • Build and configuration tools: Maven's pom.xml, .NET project files and many IDE settings.
  • Enterprise integration: SOAP web services, banking and healthcare message formats.

Each of these is easier to work with after pretty-printing.

Common mistakes

  • Unescaped special characters. A bare & or < in text makes the document not well-formed. Use &amp; and &lt;, or a CDATA section.
  • Mismatched or misnested tags. Often caused by hand-editing or string concatenation.
  • Multiple root elements. XML allows only one.
  • Wrong or missing encoding. If the declaration says UTF-8 but the file is saved in another encoding, accented characters turn into garbage.
  • Case errors. <Name> is not closed by </name>.
  • Unquoted attributes. Valid in old HTML, a fatal error in XML.
  • Forgetting namespaces in queries. Your XPath is correct but returns nothing.
  • Building XML by string concatenation. This invites escaping bugs and injection problems. Use an XML library or serializer to generate output.
  • Parsing untrusted XML with defaults. External entities can let an attacker read local files. The OWASP XXE prevention cheat sheet explains how to disable the risky features.

Step-by-step: pretty-print XML with DevUtilX

For a quick clean-up without installing anything, use the DevUtilX XML Beautifier, which runs in your browser.

  1. Open the XML beautifier tool.
  2. Paste your XML into the input editor.
  3. Choose your indentation, such as two spaces or tabs.
  4. Run the formatter and review the indented output.
  5. Copy the result into your editor, ticket or documentation.

Your data is processed locally and not uploaded, which is useful when a payload contains customer records or internal identifiers. If the formatter reports an error, the document is probably not well-formed, so look for an unclosed tag, an unescaped & or a stray character before the declaration. The XML Validator can help pinpoint the problem. When you need the opposite, use the XML Minifier to strip whitespace for transport.

Working with XML in code

Pretty-printing also exists in most languages, which is useful for logs and tests.

In JavaScript, the browser provides DOMParser and XMLSerializer:

const doc = new DOMParser().parseFromString(xmlText, "application/xml");
const error = doc.querySelector("parsererror");
if (error) throw new Error(error.textContent);
console.log(new XMLSerializer().serializeToString(doc));

In Python, the standard library can indent a parsed tree:

import xml.etree.ElementTree as ET

tree = ET.ElementTree(ET.fromstring(xml_text))
ET.indent(tree, space="  ")
tree.write("out.xml", encoding="utf-8", xml_declaration=True)

Both approaches parse first, so they also confirm that the document is well-formed. For large files, prefer a streaming parser to avoid loading everything into memory.

Best practices

  • Generate XML with a library, never by concatenating strings.
  • Declare the encoding and save the file in that encoding. UTF-8 is the safe default.
  • Indent consistently and use one element per line for data-style documents.
  • Be careful with mixed content. Do not reformat prose that contains inline tags unless you know the whitespace is irrelevant.
  • Use meaningful, consistent names. Pick one naming style, such as camelCase or kebab-case, and keep it.
  • Prefer elements for data and attributes for metadata, and be consistent about the choice.
  • Validate against a schema at system boundaries so bad data is caught early.
  • Disable external entities and DTD processing when parsing untrusted input.
  • Keep formatted source in version control, and minify only for transmission or storage when size matters.

XML compared with JSON and YAML

Aspect XML JSON YAML
Readability Verbose but explicit Compact Very compact
Comments Yes No Yes
Namespaces and schemas Mature (XSD, DTD) JSON Schema Limited
Mixed content (text and markup) Yes No No
Typical use Documents, enterprise, feeds Web APIs Configuration

JSON is usually a better fit for web APIs because it is lighter and maps directly onto JavaScript objects. XML remains the right choice where you need mixed content, namespaces, mature schema tooling or compatibility with an existing standard. The DevUtilX XML to JSON and JSON to XML tools help when you must bridge the two, and our JSON Formatting Guide covers the other side.

A short history and the design rationale

XML is a simplified subset of SGML, the Standard Generalized Markup Language, which publishers and defense contractors used for decades to manage long technical documents. SGML was powerful but hard to implement. Its grammar allowed omitted tags, shorthand syntax and many special cases, so only a few parsers handled everything correctly. The W3C working group that produced XML 1.0 in the late 1990s set out to keep SGML's core idea and throw away the complexity.

Several decisions follow from that goal, and they explain behavior that otherwise looks arbitrary:

  • Draconian error handling. A parser must stop at the first well-formedness error. The designers had watched browsers guess at broken HTML, and they wanted data exchange to be predictable instead. If every consumer rejects the same bad input, nobody builds a business on the quirks of one lenient parser.
  • Mandatory end tags. Closing every element costs a few bytes but removes ambiguity. A reader or a streaming parser always knows where an element ends.
  • Unicode from the start. XML parsers must support UTF-8 and UTF-16, and the specification defines which characters are legal in names and content. That is why XML handled international text well before many other formats did.
  • Separation of syntax and vocabulary. The core grammar says nothing about what a <book> is. Meaning comes from schemas, namespaces and the applications that read the document.

Knowing this history helps when you debate strictness. A parser that rejects your file is not being fussy. It is doing the job it was designed to do.

How an XML parser reads your document

When you hand a string to an XML library, it moves through a few stages. Understanding them makes error messages much easier to read.

  1. Decode bytes into characters. The parser looks at a byte order mark, then at the encoding in the declaration, and defaults to UTF-8 when neither is present. A mismatch here causes the garbled accents described earlier.
  2. Tokenize. The parser splits the text into start tags, end tags, text, comments and so on. A bare & fails at this stage, because the tokenizer expects an entity reference after it.
  3. Check well-formedness. It tracks open elements on a stack. Each end tag must match the element on top of the stack. This is where <a><b></a></b> fails.
  4. Resolve namespaces. Prefixes are replaced by their namespace URIs, so media:thumbnail becomes a name made of a URI plus a local name.
  5. Expose the result. Depending on the API, you receive a tree (DOM), a stream of events (SAX or pull parsing), or a data binding to objects.

You can see the failure messages directly with Python's standard library:

import xml.etree.ElementTree as ET

for bad in ["<a><b></a></b>", "<a>1 & 2</a>"]:
    try:
        ET.fromstring(bad)
    except ET.ParseError as err:
        print(err)

Running this prints mismatched tag: line 1, column 8 for the first document and not well-formed (invalid token): line 1, column 6 for the second. The line and column point to where the parser gave up, which is often slightly after the real mistake. When the reported location looks innocent, look backward for the nearest unclosed tag or unescaped character.

Reading a pretty-printed document: a worked example

Here is a response of the kind a SOAP service might return, exactly as it arrives in a log file:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GetOrderResponse xmlns="urn:example:orders"><Order id="1001" status="shipped"><Customer><Name>Grace Hopper</Name></Customer><Lines><Line sku="A1" qty="2"/><Line sku="B7" qty="1"/></Lines></Order></GetOrderResponse></soap:Body></soap:Envelope>

Pasted into a formatter, it becomes:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetOrderResponse xmlns="urn:example:orders">
      <Order id="1001" status="shipped">
        <Customer>
          <Name>Grace Hopper</Name>
        </Customer>
        <Lines>
          <Line sku="A1" qty="2"/>
          <Line sku="B7" qty="1"/>
        </Lines>
      </Order>
    </GetOrderResponse>
  </soap:Body>
</soap:Envelope>

The structure now tells a story. Three levels of wrapper (envelope, body, response) sit around the actual data, and the order has one customer and two lines. Two namespaces are in play. The envelope elements use the soap prefix. The response element declares a default namespace of urn:example:orders, and that default applies to Order, Customer, Lines and every other descendant that has no prefix.

That last point trips people up. Order has no prefix, yet it is not in "no namespace". It inherits the default from its ancestor. A query for Order without that namespace will find nothing.

Namespaces in practice: querying namespaced documents

The earlier section explained why an unprefixed XPath fails on a default-namespaced document. Here are working fixes in two common libraries.

With Python's ElementTree, pass a prefix map to the search methods. The prefix you choose is local to your code, and it does not need to match the one in the document:

import xml.etree.ElementTree as ET

xml_text = """<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Example Feed</title>
  <entry><title>First post</title></entry>
</feed>"""

root = ET.fromstring(xml_text)
ns = {"a": "http://www.w3.org/2005/Atom"}
print([t.text for t in root.findall(".//a:title", ns)])
# ['Example Feed', 'First post']

# Without the map, nothing matches:
print(root.findall(".//title"))
# []

# ElementTree also lets you write the expanded name directly:
print(root.find("{http://www.w3.org/2005/Atom}title").text)

With lxml, which supports full XPath 1.0, the idea is the same:

from lxml import etree

root = etree.fromstring(xml_text.encode("utf-8"))
titles = root.xpath("//a:title/text()", namespaces={"a": "http://www.w3.org/2005/Atom"})

You will sometimes see a shortcut like //*[local-name()='title']. It works because local-name() ignores the namespace, but it also matches elements from the wrong vocabulary. Use it for quick exploration in a console, and register proper prefixes in code that ships.

Three more namespace habits save time:

  • Declare namespaces once, at the root, unless a fragment must be self-contained. Repeating xmlns on every element bloats the file and hides the structure.
  • Attributes do not inherit the default namespace. An unprefixed attribute has no namespace, even inside a default-namespaced element. Only prefixed attributes, such as xml:lang, belong to a namespace.
  • Treat prefixes as presentation. Never write code that depends on a document using the prefix soap. A conforming sender may switch to s or env tomorrow.

Choosing a parsing model: DOM, SAX and pull parsing

The three main parsing styles trade convenience for memory.

Model How it works Memory use Best for
DOM Builds the whole tree in memory Grows with document size Small and medium files, editing, XPath queries
SAX (push) Calls your handlers as it sees each event Small and roughly constant Very large files, one forward pass
Pull (StAX style) You ask for the next event when ready Small and roughly constant Large files with code that is easier to write in a loop

A DOM is the friendliest model. You can walk up and down the tree, edit nodes and serialize the result. The cost is that the tree usually takes several times more memory than the file occupies on disk, because every node, attribute and string becomes an object. How much more depends on the library, so measure with your own data instead of trusting a rule of thumb.

Streaming avoids that cost. In Python, iterparse gives you pull-style events and lets you free finished elements:

import xml.etree.ElementTree as ET

count = 0
for event, elem in ET.iterparse("big.xml", events=("end",)):
    if elem.tag == "record":
        count += 1
        # process elem here
        elem.clear()  # release the element's children and text
print(count)

The clear() call matters. Without it, the parser keeps the whole tree alive behind you, and memory grows anyway. For files that do not fit comfortably in memory, such as exports from a database or a data warehouse, streaming is the only practical choice. It also means you cannot pretty-print the file with a DOM-based formatter. Use a streaming tool such as xmllint --format with care on huge inputs, or split the file into records first.

Formatting XML from the command line

Browser tools are convenient, but scripts and CI jobs need a command-line option. The xmllint program, part of libxml2, ships with many Linux distributions and is available through common package managers on macOS and Windows.

# Pretty-print to stdout
xmllint --format order.xml

# Pretty-print in place
xmllint --format order.xml --output order.xml

# Check well-formedness only; no output on success, exit code 1 on failure
xmllint --noout order.xml

# Validate against an XSD
xmllint --noout --schema order.xsd order.xml

Running xmllint --format on the one-line order from earlier produces two-space indentation with one element per line. The exit code makes it easy to use in scripts, because a malformed file returns a non-zero status and prints the line and column of the error.

Be aware of two behaviors. First, xmllint --format only adds indentation where it is safe, which means where an element contains only other elements. If an element has text mixed with child elements, it leaves that content alone, which protects mixed content from the whitespace problems described earlier. Second, formatting is not the same as canonicalization. The --c14n option produces Canonical XML, which sorts attributes, expands empty elements and normalizes other details so two logically equal documents become byte-identical. Canonicalization is what digital signatures use, and it is also handy for comparing documents, but its output is not meant to be pretty.

Python offers the same tool without an external program. xml.dom.minidom can pretty-print a string, though it adds an extra declaration style and blank lines in some cases, so ET.indent (shown earlier) is cleaner on Python 3.9 and newer.

Setting up formatting in your editor, pre-commit and CI

A formatter helps most when nobody has to remember to run it. Three layers work well together.

Editor. Most editors can format XML on save through a language extension or a built-in command. Set the indent size in a shared .editorconfig file so every contributor gets the same result:

[*.xml]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
insert_final_newline = true

Pre-commit. A small hook catches problems before they enter history. This one rejects any staged XML file that is not well-formed:

#!/bin/sh
# .git/hooks/pre-commit
status=0
for f in $(git diff --cached --name-only --diff-filter=ACM | grep -E '\.xml$'); do
  xmllint --noout "$f" || status=1
done
exit $status

If your team uses a hook manager, the same check can run through it, which keeps the hook under version control instead of in a local .git folder.

CI. Repeat the check on the server, because local hooks can be skipped. A formatting check can compare the file with its formatted version and fail on any difference:

for f in $(git ls-files '*.xml'); do
  xmllint --format "$f" | diff -q - "$f" > /dev/null || { echo "Not formatted: $f"; exit 1; }
done

Test this on your own repository before enforcing it. xmllint reformats the XML declaration and may change quoting or empty-element style, so a file written by a different tool can differ even when its structure is identical. Run the formatter once across the repository in a dedicated commit, then enable the check. That keeps the formatting change out of later reviews.

Reviewing XML changes in version control

Formatting rules matter most in code review. A few conventions make XML diffs readable:

  • One element per line, and one attribute per line for long tags. When an element has many attributes, putting each on its own line means adding an attribute changes one line instead of rewriting the tag.
  • Stable attribute order. Libraries may serialize attributes in insertion order, alphabetical order or hash order. If a generator reorders them between runs, every build produces noise. Pick a deterministic serializer or sort attributes before writing.
  • Stable element order where the schema allows. Sorting list items by a key, such as an id, keeps diffs small.
  • Separate formatting commits from content commits. Reviewers can then skim the first and focus on the second.

When a diff is still hard to read, compare the two versions after formatting both with the same settings. Our guide to comparing files and diffs covers tools that ignore whitespace-only changes. For generated files, you can also compare canonical forms so that harmless attribute reordering disappears.

Troubleshooting guide: symptom, cause, fix

Symptom Likely cause Fix
"Content is not allowed in prolog" or "Start tag expected" Text, a byte order mark in the wrong encoding, or whitespace before the declaration Remove anything before <?xml, and save the file as UTF-8
"XML declaration allowed only at the start of the document" A blank line or comment sits above the declaration Move the declaration to the very first byte
"Opening and ending tag mismatch" A tag is unclosed, misspelled or differs in case Check capitalization and nesting near the reported line
"EntityRef: expecting ';'" or "invalid token" A raw & in text or in a URL query string Write &amp;, or wrap the text in CDATA
"Extra content at the end of the document" A second root element, or text after the closing root tag Wrap siblings in a single root element
"Namespace prefix is not defined" A prefixed name is used with no xmlns:prefix declaration in scope Declare the prefix on the element or an ancestor
Accented characters appear as odd symbols The declared encoding differs from the real one Re-save in UTF-8 and update the declaration
XPath returns an empty result The document uses a default namespace Register the namespace and use a prefix in the query
Parser says "Document is empty" The file is empty, or a download saved an error page instead Inspect the first bytes of the file
Output loses whitespace inside a paragraph A formatter or parser trimmed mixed content Disable reformatting for that element, or use xml:space="preserve"

Wording varies between libraries, so search for the key phrase and ignore the exact text. A good debugging routine is short. Format the document if you can, check the reported line and column, then look at the few lines above it. Parsers report where they noticed the problem, and the cause is often earlier.

The URL case deserves a special note, because it is one of the most frequent real-world failures. A link such as https://example.com/search?a=1&b=2 is legal in a browser but not as XML text. Inside an attribute or element you must write https://example.com/search?a=1&amp;b=2. The parser turns &amp; back into & when it reads the value, so your code still sees the original URL.

Security considerations

Pretty-printing untrusted XML in a browser tool is low risk. Parsing it in a server application is a different story. Three attack classes come up again and again.

External entity expansion (XXE). A DTD can declare an entity whose value comes from a file or URL. A parser that resolves it may copy the contents of a local file into the document, or make network requests from your server. The fix is configuration, not input filtering. Disable DTD loading and external entity resolution in your parser, following the OWASP cheat sheet linked above. Many modern libraries now disable these features by default, but check your version and settings instead of assuming.

Entity expansion bombs. A document can define entities that reference other entities, so a tiny file expands into gigabytes of text. This is sometimes called the billion laughs attack. Libraries that limit expansion depth and size protect you. Rejecting documents that contain a DOCTYPE at all is the simplest defense when you do not need DTDs, which is true for most modern uses.

Oversized input. Deeply nested elements or very large text nodes can exhaust memory or stack space. Limit request size before parsing, and set time and memory limits on parsing jobs.

Here is a defensive setup for lxml that turns off the risky behavior:

from lxml import etree

parser = etree.XMLParser(
    resolve_entities=False,  # do not expand entities
    no_network=True,         # never fetch over the network
    load_dtd=False,          # ignore external DTDs
    huge_tree=False,         # keep libxml2's size safeguards on
)
root = etree.fromstring(untrusted_bytes, parser)

For stricter handling in Python, the third-party defusedxml package wraps the standard parsers and raises errors on dangerous constructs. Whatever library you pick, test the configuration with a document that contains an external entity reference, and confirm that it fails or is ignored.

Injection is the fourth risk, and it comes from your own code. If you build XML by joining strings with user input, a name such as </user><admin>true</admin> can alter the structure. Serializers escape data automatically, which is why the best-practices list says to use them.

Escaping, CDATA and character rules

XML text may contain most Unicode characters, but not all of them. Control characters such as a null byte or the form feed are illegal in XML 1.0, even when written as numeric references like &#0;. If a database field contains them, a serializer will either throw an error or produce a document that other parsers refuse. Strip or replace those characters before serializing.

You can always write any character with a numeric reference, in decimal (&#169;) or hexadecimal (&#xA9;) form. With UTF-8 you rarely need to, because you can write the character itself. Numeric references remain useful in ASCII-only channels.

CDATA is a convenience for humans, not a different data type. A parser delivers CDATA content as ordinary text, so your code cannot tell whether the author used CDATA or escapes. This has two consequences:

  • You cannot put the sequence ]]> inside a CDATA section. To include it, split the text across two sections.
  • Many formatters and canonicalizers convert CDATA into escaped text. Do not rely on a CDATA section surviving a round trip.

CDATA suits embedded code samples, snippets of HTML and other text full of < and &. For short values, escaping is usually clearer.

Comments have two limits. They cannot contain --, and a comment cannot end with a hyphen before the closing marker. If you generate comments from data, sanitize them first. Also remember that comments are part of the document. Do not put secrets in them, because anyone who receives the file can read them.

Attributes or elements: a decision guide

The best-practices list says to use elements for data and attributes for metadata. These tests help when a case is unclear:

  • Can the value have structure later? An element can gain children. An attribute cannot. If a price might become an amount plus a currency plus a tax rate, start with an element.
  • Can it repeat? An attribute name can appear only once per element. Lists need repeated child elements.
  • Is it long or does it contain line breaks? Attribute values undergo normalization, so newlines and tabs are converted to spaces. Use an element for multi-line text.
  • Is it an identifier or a flag that describes the element itself? Ids, units, languages and types fit attributes well.
  • Will humans diff it often? Long attribute lists make wide lines. Elements give narrower, more reviewable lines.

Here is the same record in both styles:

<!-- Attribute style: compact, harder to extend -->
<book id="b1" title="Learning XML" author="Ada Lovelace" price="29.99" currency="USD"/>

<!-- Element style: longer, easier to extend and diff -->
<book id="b1">
  <title>Learning XML</title>
  <author>Ada Lovelace</author>
  <price currency="USD">29.99</price>
</book>

The second form is the one used in this guide's first example. It keeps the id and currency as metadata, and it leaves room to add a second author or a subtitle without redesigning the format.

Schemas and validation workflow

A schema turns "this parses" into "this is acceptable". DTDs are the oldest option and are limited, since they have no namespace support and almost no data types. XSD adds types, constraints and namespaces, which makes it the common choice for enterprise integrations. RELAX NG offers a simpler grammar that many people find easier to read and write.

A practical validation workflow has four steps:

  1. Check well-formedness first. A document that does not parse cannot be validated.
  2. Validate against the schema the producer and consumer agreed on.
  3. Read errors from the top. One mistake, such as a missing required element, can trigger many follow-up errors.
  4. Validate at boundaries. Check data when it enters your system and before you send it out. Inside your own code, you can trust objects that have already passed.

Here is a minimal XSD for the order example, followed by the command that checks a file against it:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="order">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="item" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="sku" type="xs:string" use="required"/>
            <xs:attribute name="qty" type="xs:positiveInteger" use="required"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:attribute name="id" type="xs:string" use="required"/>
    </xs:complexType>
  </xs:element>
</xs:schema>
xmllint --noout --schema order.xsd order.xml

An order with qty="0" or a missing sku now fails validation, even though it is well-formed. That is the payoff: bad data is rejected with a precise message at the edge instead of causing a failure deep inside your business logic.

Generating XML safely

The advice to avoid string concatenation is easy to agree with and easy to forget under deadline. A serializer-based approach is only a few lines longer. This Python example builds an order and lets the library handle escaping:

import xml.etree.ElementTree as ET

order = ET.Element("order", id="1001")
for sku, qty in [("A1", 2), ("B7", 1)]:
    ET.SubElement(order, "item", sku=sku, qty=str(qty))

note = ET.SubElement(order, "note")
note.text = "Fragile & heavy <handle with care>"

ET.indent(order, space="  ")
print(ET.tostring(order, encoding="unicode"))

The note text comes out as Fragile &amp; heavy &lt;handle with care&gt;, with no manual escaping needed. The same pattern exists in every mainstream language. In JavaScript, build a DOM with document.implementation.createDocument and serialize it with XMLSerializer, as shown earlier.

If you must use templates, escape every interpolated value with an XML-aware escape function, and still run the result through a parser in tests. A one-line test that parses your output catches most escaping bugs before they reach production.

Accessibility and internationalization

XML itself is neutral, but documents often become content for people, so a few habits help.

  • Mark the language. Use the built-in xml:lang attribute on elements whose text differs in language from their parent. Screen readers, search engines and translation tools use it.
  • Keep content separate from presentation. XML formats like XHTML, DocBook and SVG work best when meaning is in the markup and styling lives elsewhere.
  • Provide text alternatives. In SVG, add <title> and <desc> elements so assistive technology can describe an image. Our SVG formatting and editing guide shows how to keep those elements intact when you clean up a file.
  • Use UTF-8. It covers every script, so names and addresses survive a round trip.

Right-to-left text and mixed scripts are stored in logical order. Display direction is a rendering concern, so do not reorder characters in the source.

Migration paths: converting between XML and other formats

Teams often move data from XML to JSON for new web services, or the other way around to feed older systems. Conversion is easy to start and tricky to finish, because the two models differ.

The main mismatches are:

  • Attributes versus properties. JSON has no attributes. Converters invent conventions, such as prefixing attribute names with @. Different tools choose different conventions, so settle on one and document it.
  • Repeated elements. A single <item> might become an object, while two become an array. That makes consumers fragile. Prefer converters that let you declare which elements are always lists.
  • Types. XML text is untyped, so 29.99 and true arrive as strings unless a schema tells the converter otherwise.
  • Mixed content and order. JSON objects do not guarantee element ordering across interleaved text and tags in the way XML does, and mixed content has no natural JSON shape.
  • Namespaces and comments. These usually vanish in conversion.

A safe migration plan looks like this:

  1. Inventory which parts of the XML the consumers really use.
  2. Define the target JSON shape by hand, with example documents.
  3. Convert a sample set and compare results, using the DevUtilX XML to JSON tool for quick experiments.
  4. Run both formats in parallel for a while and compare outputs.
  5. Retire the old format once consumers have moved.

Our JSON formatting guide and JSON minification guide help with the destination side.

A team formatting checklist

Agree on these points once, write them down, and enforce them with tools:

  • Indent with two spaces, with no tabs, unless an existing standard says otherwise.
  • Use UTF-8, and include the declaration when the file is stored or exchanged.
  • Place one element per line in data-oriented files.
  • Declare namespaces on the root element.
  • Choose one naming style for elements and attributes.
  • Keep attribute order deterministic.
  • Leave mixed-content elements exactly as authored.
  • Run a well-formedness check in pre-commit and CI.
  • Validate against a schema wherever a schema exists.
  • Parse untrusted input with DTD and external entity features disabled.
  • Minify only the copies you ship. Keep the readable source in version control, and see our SVG and XML minification guide for details on safe size reduction.

FAQ

Is XML dead?
No. It is less common in new web APIs, but it underpins many standards and enterprise systems, along with office formats, feeds, SVG and Android.

What is the difference between well-formed and valid XML?
Well-formed means the syntax is correct. Valid means the document is well-formed and also follows a schema. Every valid document is well-formed, but not the other way around.

Does indentation change the meaning of XML?
Usually not in data-oriented documents. In mixed content, or where xml:space is set, whitespace can matter, so review the result.

Should I use attributes or child elements?
Use elements for data and attributes for metadata about that data, such as ids and units. The most important thing is to stay consistent.

Why does my XPath query return nothing?
The most common cause is a default namespace. Register the namespace with a prefix in your XPath engine and use that prefix in the expression.

Can I put comments in XML?
Yes, with <!-- -->. Comments cannot be nested, and they should not contain a double hyphen.

Is it safe to paste XML into an online formatter?
Only if the tool runs entirely in your browser. DevUtilX processes your input locally, but always check a tool's privacy statement first.

Why does my XML file say "Content is not allowed in prolog"?
Something precedes the first < of the document, often a stray character, a blank download error page or a byte order mark in the wrong encoding. Remove it and save the file as UTF-8.

Is CDATA preserved when I reformat a file?
Not reliably. Parsers deliver CDATA as plain text, so many tools write it back as escaped text. Do not depend on CDATA surviving a round trip.

Can I format a multi-gigabyte XML file?
Not with a DOM-based tool, because it loads the whole tree. Use a streaming approach, or split the file into records and format those.

How do I compare two XML files that differ only in formatting?
Format both with the same settings, or convert both to canonical form with xmllint --c14n, then diff the results.

Conclusion

XML rewards care. A strict grammar, clear namespaces and consistent formatting make documents that people and programs can both trust. Learn the well-formed rules, use namespaces deliberately, generate XML with libraries rather than string concatenation, and pretty-print anything you need to read. For a quick clean-up of any document, try the XML Beautifier. To keep going, see our guides on HTML formatting and SQL formatting.

Further reading

Try the tools

Further reading

Related articles