simple-xml-dom
simple-xml-dom is a thin wrapper around DOMParser and XMLSerializer that makes parsing and serializing XML more pleasant. It depends on xmldom in node, and native implementations in the browser.
Install
$ npm install simple-xml-dom
note: xmldom is not installed alongside simple-xml-dom
Usage
Basic
The available methods are parse
and serialize
.
var xml = // Parse var dom = xmldomdocumentElementtextContent> 'world' // SerializedomdocumentElementtextContent = 'dexter morgan'xml> '<hello>dexter morgan</hello>'
A more modular approach
Sometimes you only need to parse
or serialize
, and in these cases it makes sense to only require a single method.
var parse = var serialize = > '<hello>world</hello>'
Format correction
XMLSerialize collapses the whitespace surrounding declarations, so the format
method exists to restore these characters.
var xml = var format = var source = '<?xml version="1.0" encoding="UTF-8"?>\r\n<hello>world</hello>' // Whitespace collapsedxml> '<?xml version="1.0" encoding="UTF-8"?><hello>world</hello>' // Whitespace restored> '<?xml version="1.0" encoding="UTF-8"?>\r\n<hello>world</hello>'
The second argument is optional. If present, whitespace from source
will be adopted by the serialize
output’s declarations. If not, a new-line character will be inserted after every declaration.