Skip to content

Instantly share code, notes, and snippets.

@DinoChiesa
Created September 26, 2023 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DinoChiesa/dba1fca8748ffcd47d41ddef91016625 to your computer and use it in GitHub Desktop.
Save DinoChiesa/dba1fca8748ffcd47d41ddef91016625 to your computer and use it in GitHub Desktop.
use of @xmldom/xmldom in JavaScript to read and update nodes in an XML document
const data = `<Foo>
<Bar baz='17'>textvalue</Bar>
<Baz>hello,world</Baz>
</Foo>`;
const xmldom = require('@xmldom/xmldom'),
DOMParser = xmldom.DOMParser,
xpath = require('xpath'),
doc = new DOMParser().parseFromString(data),
attr = xpath.select('/Foo/Bar/@baz', doc)[0],
elementText = xpath.select('/Foo/Baz/text()', doc)[0];
console.log(`attr.value=${attr.value}`);
console.log(`elementText=${elementText}`);
// attrValue=17
// elementText=hello,world
attr.value = '42'; // must be a string
const bazElement = xpath.select('/Foo/Baz', doc)[0];
bazElement.textContent = 'ciao, mondo';
const XMLSerializer = xmldom.XMLSerializer,
serialized = new XMLSerializer().serializeToString(doc);
console.log(serialized);
// <Foo>
// <Bar baz="42">textvalue</Bar>
// <Baz>ciao, mondo</Baz>
// </Foo>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment