XML Minifier

Minify XML by removing whitespace and comments

Try an example

XML Input

Minified XML

Runs locally · Safe to paste secrets
Minified XML will appear here…

What is XML Minification?

XML minification is the process of removing all unnecessary characters from an XML document without changing its meaning. An XML minifier strips whitespace between tags, removes comments, eliminates line breaks, and collapses indentation to produce compact, single-line output. The result is an XML string that parsers read identically to the original formatted version, producing the same data model.

The XML 1.0 specification (W3C Recommendation, Fifth Edition) defines whitespace handling rules in section 2.10. Whitespace between tags that has no semantic value is called "insignificant whitespace." XML processors are allowed to discard it. Whitespace inside text content, however, is significant by default unless the parent element declares xml:space="default". A correct XML minifier distinguishes between these two cases and only removes what is safe to remove.

Minification differs from compression. Gzip or Brotli reduce size at the transport layer and require decompression before parsing. Minification reduces the raw document size itself, so the XML remains valid and readable by any parser without a decompression step. In practice, minifying before compressing yields the best results: you eliminate redundant characters first, then the compression algorithm works on a tighter input.

Before · xml
After · xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Product catalog for Q1 2026 -->
<catalog>
  <product id="p101">
    <name>Widget A</name>
    <price currency="USD">29.99</price>
    <!-- Temporarily discounted -->
    <stock>142</stock>
  </product>
  <product id="p102">
    <name>Widget B</name>
    <price currency="EUR">19.50</price>
    <stock>87</stock>
  </product>
</catalog>
<?xml version="1.0" encoding="UTF-8"?><catalog><product id="p101"><name>Widget A</name><price currency="USD">29.99</price><stock>142</stock></product><product id="p102"><name>Widget B</name><price currency="EUR">19.50</price><stock>87</stock></product></catalog>

Why Use an XML Minifier?

Formatted XML with indentation and comments is ideal for development and code review. For storage, transmission, and machine consumption, that extra formatting adds bytes with no benefit. An XML minifier closes that gap.

Reduce transfer size instantly
Stripping whitespace and comments from a typical XML config file reduces its size by 20-40%. For SOAP payloads and large feeds, savings often exceed 30%, cutting bandwidth costs and API response times.
🔒
Runs client-side, no uploads
The minifier runs in the browser using the native DOMParser. No data is sent to a server. Processing happens locally regardless of what the XML contains.
📦
No signup or installation
Paste your XML, get the minified output. No account creation, no CLI tool to install, no dependencies. Works on any device with a modern browser.
🔧
Handles any well-formed XML
Supports namespaces, CDATA sections, processing instructions, and deeply nested structures. If the input is well-formed XML, the minifier will produce valid minified output.

XML Minifier Use Cases

Frontend Development
Minify SVG files embedded in HTML or CSS. Removing whitespace and comments from SVG markup reduces page weight without altering the rendered graphic. Even a modest SVG icon set can shed several kilobytes.
Backend API Optimization
Shrink SOAP responses and XML-RPC payloads before sending them to clients. Minified XML parses faster and reduces network latency for high-throughput services. The gain is largest when responses are not already compressed at the transport layer.
DevOps and CI/CD Pipelines
Minify XML configuration files (pom.xml, web.xml, .csproj) in build pipelines to reduce artifact size in Docker images and deployment packages. Smaller images translate to faster pull times and lower container registry storage bills.
QA and Testing
Normalize XML test fixtures by minifying them before comparison. Stripping formatting differences prevents false test failures caused by whitespace-only changes. Canonical minified fixtures also make version-control diffs easier to review.
Data Engineering
Compact large XML data feeds (RSS, Atom, XBRL) before storing them in databases or message queues. Smaller payloads mean lower storage costs and faster queue throughput. At scale, a 20% reduction in feed size adds up quickly in compute and I/O costs.
Learning XML Structure
Students can minify and then re-format XML to understand how parsers ignore insignificant whitespace and why the document structure is independent of its visual formatting. This exercise makes abstract spec rules concrete and immediately observable.

What XML Minification Removes

Not everything in an XML document can be safely removed. This reference table shows each type of removable content and whether discarding it is always safe or conditional on your use case.

ItemExampleSafety
IndentationSpaces/tabs before tagsAlways safe to remove
Line breaks\n and \r\n between tagsAlways safe to remove
Comments<!-- ... -->Safe unless parsed by app
XML declaration<?xml version="1.0"?>Keep if encoding is non-UTF-8
Processing instructions<?xml-stylesheet ...?>Keep if consumed downstream
Trailing whitespaceSpaces after closing tagsAlways safe to remove
Text node whitespaceSpaces inside text contentRemove only between tags, not within

Minification vs Gzip vs Binary Formats

Minification, compression, and binary encoding each target a different layer of the size problem. Minification keeps the output as valid, human-readable XML. Compression (gzip, Brotli) shrinks further but requires a decompression step before parsing. Binary formats go furthest, but both ends of the connection need a compatible encoder/decoder — practical mainly for embedded systems or WSDL-heavy enterprise services.

XML Minification
Removes insignificant whitespace, comments, and line breaks. Output is still valid XML, readable by any parser. Typical reduction: 20-40%. No decompression step needed.
Gzip / Brotli Compression
Applies a compression algorithm to the byte stream. Typical reduction: 60-80% on top of minification. Requires a decompression step before the XML can be parsed. Standard for HTTP via Content-Encoding.
Binary Formats (EXI, Fast Infoset)
Encode the XML Infoset in a binary representation. Typical reduction: 80-95%. Requires a compatible encoder/decoder on both sides. Used in constrained environments like embedded systems and WSDL-heavy services.

Code Examples

Minifying XML programmatically follows the same pattern in every language: parse the document into a tree, optionally remove comment nodes, then serialize without indentation.

JavaScript (browser)
// Minify XML by parsing and re-serializing (strips formatting)
const raw = `<root>
  <item id="1">
    <!-- note -->
    <name>Test</name>
  </item>
</root>`

const parser = new DOMParser()
const doc = parser.parseFromString(raw, 'application/xml')

// Remove comment nodes
const walker = doc.createTreeWalker(doc, NodeFilter.SHOW_COMMENT)
const comments = []
while (walker.nextNode()) comments.push(walker.currentNode)
comments.forEach(c => c.parentNode.removeChild(c))

const minified = new XMLSerializer().serializeToString(doc)
// → "<root><item id=\"1\"><name>Test</name></item></root>"
Python
from lxml import etree

xml = """<root>
  <item id="1">
    <!-- note -->
    <name>Test</name>
  </item>
</root>"""

tree = etree.fromstring(xml.encode())

# Remove comments
for comment in tree.iter(etree.Comment):
    comment.getparent().remove(comment)

# Serialize without pretty-print (minified)
result = etree.tostring(tree, xml_declaration=False).decode()
# → '<root><item id="1"><name>Test</name></item></root>'

# With xml.etree (stdlib, no lxml needed)
import xml.etree.ElementTree as ET
root = ET.fromstring(xml)
ET.indent(root, space='')  # Python 3.9+
print(ET.tostring(root, encoding='unicode'))
Go
package main

import (
    "encoding/xml"
    "fmt"
    "strings"
)

func minifyXML(input string) (string, error) {
    decoder := xml.NewDecoder(strings.NewReader(input))
    var out strings.Builder
    encoder := xml.NewEncoder(&out)
    // No indentation = minified output
    for {
        tok, err := decoder.Token()
        if err != nil {
            break
        }
        // Skip comments
        if _, ok := tok.(xml.Comment); ok {
            continue
        }
        // Skip whitespace-only char data
        if cd, ok := tok.(xml.CharData); ok {
            if strings.TrimSpace(string(cd)) == "" {
                continue
            }
        }
        encoder.EncodeToken(tok)
    }
    encoder.Flush()
    return out.String(), nil
}
// minifyXML("<a>\n  <b>1</b>\n</a>") → "<a><b>1</b></a>"
CLI (xmllint)
# Minify XML with xmllint (part of libxml2)
xmllint --noblanks input.xml > minified.xml

# Minify from stdin
echo '<root>
  <item>hello</item>
</root>' | xmllint --noblanks -
# → <?xml version="1.0"?><root><item>hello</item></root>

# Strip comments too (combine with sed or xmlstarlet)
xmlstarlet ed -d '//comment()' input.xml | xmllint --noblanks -

# Check size reduction
echo "Before: $(wc -c < input.xml) bytes"
echo "After:  $(xmllint --noblanks input.xml | wc -c) bytes"

Frequently Asked Questions

Is minified XML still valid XML?
Yes. Minification only removes insignificant whitespace and comments. The resulting document conforms to the same XML 1.0 or 1.1 specification as the original. Any compliant parser will produce the same data model from both the formatted and minified versions.
How much smaller does XML get after minification?
Savings vary based on how the original was formatted. Heavily indented XML with comments typically shrinks by 20–40%. A document already compact may only lose 5–10%. Compare byte counts of input and output to measure the exact reduction.
Can minification break my XML?
If the minifier only removes whitespace between tags (insignificant whitespace) and comments, the document semantics stay the same. The one edge case is xml:space="preserve" sections, where whitespace inside text nodes is meaningful. A correct minifier respects this directive and leaves those sections untouched.
What is the difference between XML minification and XML compression?
Minification edits the XML text itself by removing characters that carry no data. Compression (gzip, Brotli) encodes the entire byte stream into a smaller binary format that must be decompressed before parsing. Minification and compression are complementary: minify first, then compress for transport.
Should I minify XML before storing it in a database?
For large volumes of XML data, minifying before storage reduces disk usage and speeds up reads. For configuration files or templates that developers edit by hand, store the formatted version and minify at build time or on the wire. The tradeoff is readability vs. storage efficiency. Avoid minifying XML that will be audited, diffed in version control, or manually updated by operations teams — preserving formatting in those cases saves far more time than the storage savings are worth.
Does xmllint support minification?
Yes. Running xmllint --noblanks input.xml strips insignificant whitespace. It does not remove comments by default. To remove comments as well, pipe through xmlstarlet ed -d '//comment()' first, or use a custom XSLT that strips comment nodes.
How does minification affect XML parsing performance?
Minified XML parses faster because the parser processes fewer bytes and encounters no whitespace-only text nodes. The difference is most noticeable on large documents (1 MB+) and in streaming parsers, where each extra node adds to traversal overhead.