XML
suggest changeJSON has replaced XML for most new APIs, but XML is still everywhere: RSS and Atom feeds, sitemaps, SOAP services, SVG, Office documents (.docx, .xlsx), Maven and .NET project files, Android layouts, bank and government data exchange formats.
Unlike browsers, Node.js has no built-in XML parser: there is no DOMParser and no XMLSerializer. You need a package. The common choices are:
| Package | Style | Good for |
|---|---|---|
| fast-xml-parser | XML to plain JS object and back | most tasks: config files, feeds, API responses |
| xmlbuilder2 | fluent builder, DOM | generating XML, editing documents |
| @xmldom/xmldom + xpath | W3C DOM and XPath | complex documents, namespaces, queries |
| saxes | streaming SAX events | huge files that don't fit in memory |
All examples use ES modules and were run with Node.js 24, fast-xml-parser 5, xmlbuilder2 4, @xmldom/xmldom 0.9 and saxes 6:
npm install fast-xml-parser xmlbuilder2 @xmldom/xmldom xpath saxes
For JSON see JSON. For HTML, which is not XML and needs a forgiving parser, see Parsing HTML.
Parsing XML into objects
fast-xml-parser turns XML into nested plain objects, which is the easiest form to work with in JavaScript:
import { XMLParser } from 'fast-xml-parser';
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="1" lang="en">
<title>Dune</title>
<author>Frank Herbert</author>
<year>1965</year>
<price>9.99</price>
</book>
<book id="2" lang="pl">
<title>Solaris</title>
<author>Stanisław Lem</author>
<year>1961</year>
<price>12.50</price>
</book>
</library>`;
const parser = new XMLParser();
const doc = parser.parse(xml);
console.log(JSON.stringify(doc, null, 2));
console.log(doc.library.book[1].title); // Solaris
console.log(typeof doc.library.book[0].year); // number
Output:
{
"?xml": "",
"library": {
"book": [
{
"title": "Dune",
"author": "Frank Herbert",
"year": 1965,
"price": 9.99
},
{
"title": "Solaris",
"author": "Stanisław Lem",
"year": 1961,
"price": 12.5
}
]
}
}
Things to notice:
- repeated elements (
<book>) become an array - text that looks like a number is converted to a number
- attributes (
id,lang) are dropped by default
Attributes
Set ignoreAttributes: false to keep attributes. They are stored next to child elements, with a prefix so they don't collide with element names:
import { XMLParser } from 'fast-xml-parser';
const xml = `<library>
<book id="1" lang="en"><title>Dune</title><isbn>0441013597</isbn></book>
<book id="2" lang="pl"><title>Solaris</title><isbn>0156027607</isbn></book>
</library>`;
const parser = new XMLParser({
ignoreAttributes: false, // keep attributes
attributeNamePrefix: '@_', // default prefix, shown for clarity
});
const doc = parser.parse(xml);
console.log(doc.library.book[0]);
// { title: 'Dune', isbn: 441013597, '@_id': '1', '@_lang': 'en' }
Attribute values stay strings ('1') unless you set parseAttributeValue: true. Notice also the bug in isbn: the leading zero is gone. More on that below.
When an element has both attributes and text, the text goes into a #text property: <total currency="EUR">19.90</total> becomes { '#text': 19.9, '@_currency': 'EUR' }.
One element or many: always use isArray
The most common bug with object-based XML parsing: an element that appears once becomes an object, an element that appears many times becomes an array. Code that works on test data with two items crashes in production on a feed with one item:
import { XMLParser } from 'fast-xml-parser';
const one = '<library><book><title>Dune</title></book></library>';
const two = '<library><book><title>Dune</title></book><book><title>Emma</title></book></library>';
const naive = new XMLParser();
console.log(naive.parse(one).library.book); // { title: 'Dune' }
console.log(naive.parse(two).library.book); // [ { title: 'Dune' }, { title: 'Emma' } ]
const parser = new XMLParser({
isArray: (name, jpath) => jpath === 'library.book',
});
console.log(parser.parse(one).library.book); // [ { title: 'Dune' } ]
console.log(parser.parse(two).library.book.map((b) => b.title)); // [ 'Dune', 'Emma' ]
isArray(tagName, jpath, isLeafNode, isAttribute) is called for every element. jpath is the dotted path from the root. Return true for every element that can repeat according to the format you are reading.
Values: numbers, strings and lost zeros
Automatic number conversion is convenient for <year>1965</year> but destroys data that only looks numeric: zip codes, phone numbers, IDs, ISBNs. When the data matters, turn it off with parseTagValue: false and convert values yourself:
import { XMLParser } from 'fast-xml-parser';
const xml = `<order>
<zip>02134</zip>
<phone>+48123456789</phone>
<qty>3</qty>
<total currency="EUR">19.90</total>
<empty/>
</order>`;
const auto = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '' });
console.log(auto.parse(xml).order);
const strict = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '',
parseTagValue: false, // keep all text as strings
});
const order = strict.parse(xml).order;
console.log(order);
console.log(Number(order.qty) * Number(order.total['#text']));
Output:
{
zip: 2134,
phone: 48123456789,
qty: 3,
total: { '#text': 19.9, currency: 'EUR' },
empty: ''
}
{
zip: '02134',
phone: '+48123456789',
qty: '3',
total: { '#text': '19.90', currency: 'EUR' },
empty: ''
}
59.699999999999996
Note that the default parser turned +48123456789 into a number and 02134 into 2134.
Entities and CDATA
The five predefined XML entities (&, <, >, ", ') and entities declared in the document's DOCTYPE are decoded. Numeric character references such as © are decoded only with htmlEntities: true. CDATA sections are returned as plain text, or under a separate key with cdataPropName:
import { XMLParser } from 'fast-xml-parser';
const xml = `<msg>
<text>Tom & Jerry <3 © café</text>
<code><![CDATA[if (a < b && c > d) {}]]></code>
</msg>`;
console.log(new XMLParser().parse(xml).msg);
// { text: 'Tom & Jerry <3 © café', code: 'if (a < b && c > d) {}' }
console.log(new XMLParser({ htmlEntities: true }).parse(xml).msg.text);
// Tom & Jerry <3 © café
Mixed content
Object mapping works well for data-oriented XML. It doesn't work for document-oriented XML, where text and elements are interleaved:
import { XMLParser } from 'fast-xml-parser';
const xml = '<note>Leave at <b>door</b> please</note>';
console.log(new XMLParser().parse(xml));
// { note: { b: 'door', '#text': 'Leave atplease' } }
The order and spacing are lost. For XHTML, DocBook, SVG text and similar documents use preserveOrder: true (which produces a verbose array-of-nodes format) or, better, a DOM parser as shown later.
Validating XML
XMLParser is lenient and does not check well-formedness by default. Broken XML can silently produce a wrong object:
import { XMLParser, XMLValidator } from 'fast-xml-parser';
const bad = '<user><name>Ann</name><age>30</user>';
console.log(new XMLParser().parse(bad));
// { user: { name: 'Ann', age: 30 } }
const result = XMLValidator.validate(bad);
if (result !== true) {
console.log(result.err);
}
// or pass true as the second argument to validate before parsing
try {
new XMLParser().parse(bad, true);
} catch (err) {
console.log('parse failed:', err.message);
}
Output:
{ user: { name: 'Ann', age: 30 } }
{
code: 'InvalidTag',
msg: "Expected closing tag 'age' (opened in line 1, col 23) instead of closing tag 'user'.",
line: 1,
col: 30
}
parse failed: Expected closing tag 'age' (opened in line 1, col 23) instead of closing tag 'user'.:1:30
Always validate XML that comes from outside your program. Note that this checks well-formedness only (matching tags, quoted attributes, legal names). Validation against an XSD schema or DTD requires a different tool, such as libxmljs2 (a native binding to libxml2) or running xmllint as a child process.
Reading and writing XML files
Combine the parser with fs/promises. XMLBuilder converts the object back to XML; pass it the same options as the parser so attributes and arrays round-trip:
import { readFile, writeFile } from 'node:fs/promises';
import { XMLParser, XMLBuilder } from 'fast-xml-parser';
const options = {
ignoreAttributes: false,
isArray: (name, jpath) => jpath === 'settings.recent.file',
};
const settings = new XMLParser(options).parse(await readFile('settings.xml', 'utf8'));
settings.settings.fontSize += 2;
settings.settings.recent.file.unshift('b.txt');
await writeFile('settings.xml', new XMLBuilder({ ...options, format: true }).build(settings));
console.log(await readFile('settings.xml', 'utf8'));
Output:
<settings>
<theme>dark</theme>
<fontSize>16</fontSize>
<recent>
<file>b.txt</file>
<file>a.txt</file>
</recent>
</settings>
Comments, formatting and the order of mixed elements in the original file are not preserved by a parse/build round-trip. If you edit files that people also edit by hand, use a DOM (xmlbuilder2 or xmldom) instead.
Fetching XML over HTTP
fetch is built into Node.js. Read the body with res.text() and parse it. Here we read the Node.js blog's RSS feed:
import { XMLParser } from 'fast-xml-parser';
const res = await fetch('https://nodejs.org/en/feed/blog.xml');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const parser = new XMLParser({ isArray: (name, jpath) => jpath === 'rss.channel.item' });
const feed = parser.parse(await res.text());
for (const item of feed.rss.channel.item.slice(0, 3)) {
console.log(`${new Date(item.pubDate).toISOString().slice(0, 10)} ${item.title}`);
}
Output (at the time of writing):
2026-10-14 Node.js 24.22.0 (LTS)
2026-10-14 Node.js 26.12.0 (Current)
2026-10-14 Wednesday, October 21, 2026 Security Releases
Generating XML
With XMLBuilder
XMLBuilder takes the same object shape the parser produces. Keys with the attribute prefix become attributes, arrays become repeated elements, and special characters in text and attributes are escaped:
import { XMLBuilder } from 'fast-xml-parser';
const data = {
'?xml': { '@_version': '1.0', '@_encoding': 'UTF-8' },
library: {
book: [
{ '@_id': 1, title: 'Dune', author: 'Frank Herbert', year: 1965 },
{ '@_id': 2, title: 'Tom & Jerry <Collected>', author: 'Various', year: 1940 },
],
},
};
const builder = new XMLBuilder({
ignoreAttributes: false,
format: true, // pretty print
indentBy: ' ',
});
console.log(builder.build(data));
Output:
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="1">
<title>Dune</title>
<author>Frank Herbert</author>
<year>1965</year>
</book>
<book id="2">
<title>Tom & Jerry <Collected></title>
<author>Various</author>
<year>1940</year>
</book>
</library>
With xmlbuilder2
xmlbuilder2 has a fluent API that reads like the document it generates. ele() creates a child element and returns it, att() sets an attribute, txt() adds text, up() returns to the parent:
import { create } from 'xmlbuilder2';
const items = [
{ title: 'Release 2.0', link: 'https://example.com/2.0', date: new Date(Date.UTC(2026, 9, 1)) },
{ title: 'Fixes & tweaks', link: 'https://example.com/1.9', date: new Date(Date.UTC(2026, 8, 12)) },
];
const channel = create({ version: '1.0', encoding: 'UTF-8' })
.ele('rss', { version: '2.0' })
.ele('channel')
.ele('title').txt('Example blog').up()
.ele('link').txt('https://example.com').up();
for (const item of items) {
channel
.ele('item')
.ele('title').txt(item.title).up()
.ele('link').txt(item.link).up()
.ele('pubDate').txt(item.date.toUTCString()).up()
.up();
}
console.log(channel.end({ prettyPrint: true }));
Output:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Example blog</title>
<link>https://example.com</link>
<item>
<title>Release 2.0</title>
<link>https://example.com/2.0</link>
<pubDate>Thu, 01 Oct 2026 00:00:00 GMT</pubDate>
</item>
<item>
<title>Fixes & tweaks</title>
<link>https://example.com/1.9</link>
<pubDate>Sat, 12 Sep 2026 00:00:00 GMT</pubDate>
</item>
</channel>
</rss>
end() serializes the whole document no matter which node you call it on.
xmlbuilder2 can also parse existing XML into a document you can modify, or convert it to an object:
import { create } from 'xmlbuilder2';
const doc = create('<config><server host="localhost" port="8080"/><debug>true</debug></config>');
console.log(doc.end({ format: 'object' }));
// { config: { server: { '@host': 'localhost', '@port': '8080' }, debug: 'true' } }
doc.root().first().att('port', '9090');
doc.root().ele('logLevel').txt('info');
console.log(doc.end({ prettyPrint: true, headless: true }));
Output:
<config>
<server host="localhost" port="9090"/>
<debug>true</debug>
<logLevel>info</logLevel>
</config>
headless: true omits the <?xml ...?> declaration.
By hand, with escaping
For a small fixed template, a library isn't necessary, but you must escape every interpolated value. Forgetting to do it produces broken XML at best and an injection vulnerability at worst. A tagged template makes escaping automatic:
const XML_ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
function escapeXml(value) {
return String(value).replace(/[&<>"']/g, (ch) => XML_ESCAPES[ch]);
}
function xml(strings, ...values) {
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? escapeXml(values[i]) : ''),
''
);
}
const user = { name: "O'Brien & Sons", note: '<script>alert(1)</script>' };
console.log(xml`<user name="${user.name}"><note>${user.note}</note></user>`);
// <user name="O'Brien & Sons"><note><script>alert(1)</script></note></user>
DOM and XPath
For documents with namespaces, mixed content or deep structures, a W3C DOM plus XPath queries is often simpler than walking objects. @xmldom/xmldom implements the same DOMParser and XMLSerializer API as browsers, and xpath adds XPath 1.0:
import { DOMParser, XMLSerializer } from '@xmldom/xmldom';
import xpath from 'xpath';
const xml = `<library>
<book id="1" lang="en"><title>Dune</title><price>9.99</price></book>
<book id="2" lang="pl"><title>Solaris</title><price>12.50</price></book>
<book id="3" lang="en"><title>Emma</title><price>4.25</price></book>
</library>`;
const doc = new DOMParser().parseFromString(xml, 'text/xml');
// standard DOM API
for (const book of Array.from(doc.getElementsByTagName('book'))) {
const title = book.getElementsByTagName('title')[0].textContent;
console.log(book.getAttribute('id'), title);
}
// XPath queries
const english = xpath.select('//book[@lang="en"]/title/text()', doc);
console.log(english.map((n) => n.data)); // [ 'Dune', 'Emma' ]
const cheap = xpath.select('//book[price < 10]/@id', doc);
console.log(cheap.map((a) => a.value)); // [ '1', '3' ]
console.log(xpath.select('count(//book)', doc)); // 3
console.log(xpath.select1('string(//book[@id="2"]/title)', doc)); // Solaris
// modify and serialize
doc.getElementsByTagName('book')[0].setAttribute('lang', 'en-US');
console.log(new XMLSerializer().serializeToString(doc).split('\n')[1]);
// <book id="1" lang="en-US"><title>Dune</title><price>9.99</price></book>
Namespaces
Many real formats (Atom, SOAP, SVG, Office XML) put elements in a namespace. An XPath expression without a prefix only matches elements with no namespace, so a naive query silently finds nothing. Bind prefixes with xpath.useNamespaces():
import { DOMParser } from '@xmldom/xmldom';
import xpath from 'xpath';
const xml = `<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example</title>
<entry><title>First post</title><id>urn:1</id></entry>
<entry><title>Second post</title><id>urn:2</id></entry>
</feed>`;
const doc = new DOMParser().parseFromString(xml, 'text/xml');
console.log(xpath.select('//entry', doc).length); // 0, entry is in the Atom namespace
const select = xpath.useNamespaces({ atom: 'http://www.w3.org/2005/Atom' });
const titles = select('//atom:entry/atom:title/text()', doc);
console.log(titles.map((n) => n.data)); // [ 'First post', 'Second post' ]
The prefix you choose (atom) doesn't have to match the one in the document; only the namespace URI matters.
Parse errors
parseFromString throws a ParseError on fatal errors such as mismatched tags, but it also logs every problem to the console and tolerates some errors (like an unescaped &). Pass onError to collect messages instead of logging them:
import { DOMParser } from '@xmldom/xmldom';
const problems = [];
const parser = new DOMParser({
onError: (level, msg) => problems.push(`${level}: ${msg.split('\n')[0]}`),
});
try {
parser.parseFromString('<a><b></a>', 'text/xml');
} catch (err) {
console.log(err.name, '-', err.message.split('\n')[0]);
}
// ParseError - Opening and ending tag mismatch: "b" != "a"
If you need strict well-formedness, run XMLValidator.validate() from fast-xml-parser first.
Streaming large files
All the approaches above load the whole document into memory. That's fine for a few megabytes, but for a multi-gigabyte export (Wikipedia dumps, product catalogs, OpenStreetMap data) use a streaming SAX parser. It reads the input in chunks and emits events for each opening tag, piece of text and closing tag. You keep only the state you need.
This example processes a 7.7 MB file with 100,000 products while using about 10 MB of heap:
import { createReadStream } from 'node:fs';
import { SaxesParser } from 'saxes';
async function sumPrices(path) {
const parser = new SaxesParser();
let count = 0;
let total = 0;
let current = null; // product being built
let text = '';
parser.on('opentag', (node) => {
if (node.name === 'product') current = { sku: node.attributes.sku };
text = '';
});
parser.on('text', (t) => { text += t; });
parser.on('closetag', (node) => {
if (!current) return;
if (node.name === 'name') current.name = text;
else if (node.name === 'price') current.price = Number(text);
else if (node.name === 'product') {
count++;
total += current.price;
current = null;
}
});
for await (const chunk of createReadStream(path, { encoding: 'utf8' })) {
parser.write(chunk); // throws on malformed XML
}
parser.close();
return { count, total };
}
const { count, total } = await sumPrices('products.xml');
console.log(count, total.toFixed(2));
console.log(`heap used: ${Math.round(process.memoryUsage().heapUsed / 1e6)} MB`);
Output:
100000 2549000.00
heap used: 10 MB
The input looks like <products><product sku="P1"><name>Item 1</name><price>1.99</price></product>...</products>.
A text event can arrive in several pieces when a chunk boundary falls inside text, which is why the code appends to text and uses it only on closetag. saxes is strict: it throws on malformed input, with line and column:
import { SaxesParser } from 'saxes';
try {
new SaxesParser().write('<a><b></a>').close();
} catch (err) {
console.log(err.message); // 1:10: unexpected close tag.
}
For more on streams see Using streams.
Security
XML parsers have a history of serious vulnerabilities. When parsing untrusted input:
- External entities (XXE). A DOCTYPE like
<!ENTITY xxe SYSTEM "file:///etc/passwd">asks the parser to read a local file or URL and insert it into the document. fast-xml-parser refuses: it throwsExternal entities are not supported. xmldom and saxes don't fetch external resources either. Be careful with native libxml2 bindings, where entity substitution must stay disabled. - Entity expansion ("billion laughs"). Nested entity definitions can expand a 1 KB document into gigabytes. fast-xml-parser doesn't expand entities that reference other entities. If you don't need DOCTYPE entities at all, set
processEntities: false. - Size. Limit the request body size before parsing (for example
express.text({ type: 'application/xml', limit: '1mb' })) and stream large inputs instead of buffering them. - Prototype keys. Element names become object keys. fast-xml-parser 5 throws on names like
__proto__andconstructorand renamestoStringorhasOwnPropertyto__toStringand__hasOwnProperty, so expect parse errors on hostile input. Even so, read values from parsed objects by known paths instead of merging them blindly into other objects.
Summary
| Task | Code |
|---|---|
| XML to object | new XMLParser().parse(xml) |
| keep attributes | new XMLParser({ ignoreAttributes: false }) |
| element is always an array | isArray: (name, jpath) => jpath === 'a.b' |
| keep text as strings | parseTagValue: false |
| check well-formedness | XMLValidator.validate(xml) |
| object to XML | new XMLBuilder({ ignoreAttributes: false, format: true }).build(obj) |
| fluent XML generation | create().ele('a').att('k', 'v').txt('x').end({ prettyPrint: true }) |
| DOM | new DOMParser().parseFromString(xml, 'text/xml') |
| XPath | xpath.select('//book/title/text()', doc) |
| XPath with namespaces | xpath.useNamespaces({ p: 'uri' })('//p:el', doc) |
| huge files | SaxesParser with opentag / text / closetag events |