I want to delete a node with a particular name attribute specified by a user. What am I doing wrong? Let's sat user enters: "cat" and whenever system finds an animal with an attribute cat it deletes it. Animal nodes have no children.
This is a simplification of the .xml file
<animals>
<animal name="elephant"></animal>
<animal name="cat"></animal>
...
</animals>
This is my code for deleting a particular node from xml file.
function delete() {
xmlDoc = loadXMLDoc("file.xml");
root = xmlDoc.getElementsByTagName("animal");
for (i = 0; i < root.length; i++) {
if (root[i].nodeType == 1) {
if (root[i].attributes[0].value == document.getElementById("del").value) {
xmlDoc.removeChild(root[i]);
display(); // function displaying the results
}
}
}
}
Your <animal>
nodes are not children of the top-level node in the XML DOM, so xmlDoc.removeChild()
won't work.
root[i].parentNode.removeChild(root[i]);
That said, you'll probably run into difficulties due to the fact that the node list returned from getElementsByTagName()
is live. As you remove elements, the list will shrink and you'll wind up skipping some. You can change the loop to deal with that:
for (var i=0; i<root.length; ) {
if(root[i].nodeType==1 && root[i].attributes[0].value==document.getElementById("del").value) {
xmlDoc.removeChild(root[i]);
display(); // function displaying the results
}
else
i++;
}