What is xmldom?
The xmldom npm package is a pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module. It allows users to parse XML data into a DOM tree structure and serialize DOM trees back into XML. This package is particularly useful for server-side applications where DOM manipulation is needed without a browser environment.
What are xmldom's main functionalities?
Parsing XML to DOM
This feature allows you to parse a string of XML into a DOM tree, enabling programmatic access and manipulation of the structure and content.
const { DOMParser } = require('xmldom');
const xmlString = '<root>Hello World</root>';
const doc = new DOMParser().parseFromString(xmlString, 'text/xml');
console.log(doc.documentElement.nodeName); // 'root'
Serializing DOM to XML
This feature enables you to take a DOM tree and serialize it back into a string of XML, useful for outputting modified XML data.
const { XMLSerializer } = require('xmldom');
const doc = new DOMParser().parseFromString('<root>Hello World</root>', 'text/xml');
const xmlString = new XMLSerializer().serializeToString(doc);
console.log(xmlString); // '<root>Hello World</root>'
Other packages similar to xmldom
libxmljs
libxmljs is a native library for parsing and manipulating XML. It offers faster performance due to its native implementation but requires compilation, which can be a downside compared to the pure JavaScript implementation of xmldom.
cheerio
cheerio is primarily used for web scraping and server-side manipulation of HTML. While it can handle XML and offers a jQuery-like syntax for manipulation, it's more tailored towards HTML content. Compared to xmldom, cheerio might be more user-friendly for those familiar with jQuery but less strict in terms of XML standards compliance.
Introduction
Another xml parser for nodejs/browser/rhino for java.
Fully compatible with W3C DOM level2
; and some compatible with level3
.
support DOMParser
and XMLSerializer
interface such as in browser.
Install:
npm install xmldom
Example:
var DOMParser = require('xmldom').DOMParser;
var doc = new DOMParser().parseFromString(
'<xml xmlns="a" xmlns:c="./lite">\n'+
'\t<child>test</child>\n'+
'\t<child></child>\n'+
'\t<child/>\n'+
'</xml>'
,'text/xml');
doc.documentElement.setAttribute('x','y');
doc.documentElement.setAttributeNS('./lite','c:x','y2');
var nsAttr = doc.documentElement.getAttributeNS('./lite','x')
console.info(nsAttr)
console.info(doc)