minify-xml
minify-xml is a lightweight and fast XML minifier for NodeJS with a command line.
Existing XML minifiers, such as pretty-data often do a pretty (phun intended) bad job minifying XML in usually only removing comments and whitespace between tags. minify-xml on the other hand also includes minification of tags, e.g. by collapsing the whitespace between multiple attributes and further minifications, such as the removal of unused namespace declarations. minify-xml is based on regular expressions and thus executes blazingly fast.
Online
Use this package online to minify XMLs in your browser, visit:
Minify-X.ML (https://minify-x.ml/)
Installation
npm install minify-xml -gUsage
import minifyXML from "minify-xml";
const xml = `<Tag xmlns:used = "used_ns" xmlns:unused = "unused_ns">
<!--
With the default options all comments will be removed, whitespace in
tags, like spaces between attributes, will be collapsed / removed and
elements without any content will be collapsed to empty tag elements
-->
<AnotherTag attributeA = "..." attributeB = "..." > </AnotherTag >
<!--
Also any unused namespaces declarations will be removed by default,-- <used:NamespaceTag used:attribute = "..." any valid element content is left unaffected (strangely enough = " ... " and even are valid characters in XML, only < must always be encoded) </used:NamespaceTag
<![CDATA[<FakeTag attr = "content in CDATA tags is not minified"</FakeTag]] </Tag;
console.log(minifyXML(xml));
This outputs the minified XML:
<Tag xmlns:u="usedns"<AnotherTag attributeA="..." attributeB="..."/<u:NamespaceTag u:attribute="..." any valid element content is left unaffected (strangely enough = " ... " and even are valid characters in XML, only < must always be encoded) </u:NamespaceTag<![CDATA[<FakeTag attr = "content in CDATA tags is not minified"</FakeTag]]</Tag
Alternatively a [Node.js `Transform` stream](https://nodejs.org/api/stream.html#stream_class_stream_transform) can be provided to minify XML streams, which is especially helpful for very large files (> 2 GiB, which is the maximum `Buffer` size in Node.js on 64-bit machines):
import { minifyStream as minifyXMLStream } from "minify-xml";
fs.createReadStream("sitemap.xml", "utf8") .pipe(minifyXMLStream()) .pipe(process.stdout);