How to change XML Attribute in Javascript?
Working with XML in JavaScript
/*
This code comes from Vincent Lab
And it has a video version linked here: https://www.youtube.com/watch?v=5YQXVgNZvRk
*/
// Import dependencies
const fs = require("fs");
const { parseString, Builder } = require("xml2js");
// Load the XML
const xml = fs.readFileSync("data.xml").toString();
parseString(xml, function (err, data) {
// Show the XML
console.log(data);
// Modify the XML
data.people.person[0].$.id = 2;
// Saved the XML
const builder = new Builder();
const xml = builder.buildObject(data);
fs.writeFileSync("data.xml", xml, function (err, file) {
if (err) throw err;
console.log("Saved!");
});
});
The way to change the value of an attribute, is to change its text value. This can be done using the setAttribute() method or setting the nodeValue property of the attribute node.
The following code fragment loads "books.xml" into xmlDoc and adds an "edition" attribute to all
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, i, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName('title');
// Add a new attribute to each title element
for (i = 0; i < x.length; i++) {
x[i].setAttribute("edition", "first");
}
// Output titles and edition value
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue +
" - Edition: " +
x[i].getAttribute('edition') + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
Output
Everyday Italian - Edition: first
Harry Potter - Edition: first
XQuery Kick Start - Edition: first
Learning XML - Edition: first
Harry Potter - Edition: first
XQuery Kick Start - Edition: first
Learning XML - Edition: first