-
-
Save iqbmo04/14be6e29d7d3e924190150e4e3a2a051 to your computer and use it in GitHub Desktop.
use of @xmldom/xmldom in JavaScript to read and update nodes in an XML document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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