myData.xml
<?xml version='1.0'?>
<root>
<data>
<animal>Lion</animal>
<habitat>jungle</habitat>
<type>mammal</type>
<eatingHabit>Carnivore</eatingHabit>
</data>
<data>
<animal>Deer</animal>
<habitat>jungle</habitat>
<type>mammal</type>
<eatingHabit>Herbivore</eatingHabit>
</data>
</root>
myData.html
<!DOCTYPE html>
<html>
<body>
<h1>Adding Element </h1>
<script>
function loadFile(name){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",name,false);
xmlhttp.send();
return xmlhttp.responseXML;
}
xmlDoc = loadFile("myData.xml");
x=xmlDoc.getElementsByTagName("data");
newEle=xmlDoc.createElement("FeedOn");
newtxt = xmlDoc.createTextNode("Prey");
newEle.appendChild(newtxt);
x[0].appendChild(newEle);
newEle=xmlDoc.createElement("FeedOn");
newtxt = xmlDoc.createTextNode("Grass");
newEle.appendChild(newtxt);
x[1].appendChild(newEle);
y = xmlDoc.getElementsByTagName("animal");
z = xmlDoc.getElementsByTagName("FeedOn");
for (i=0; i<y.length; i++)
{
document.write(y[i].childNodes[0].nodeValue + " - Added node: FeedOn - " + z[i].childNodes[0].nodeValue + "<br/>")
}
document.write("animal has child nodes:" + y[0].hasChildNodes() + "<br/>");
document.write("data has child nodes:" + x[1].hasChildNodes());
</script>
</body>
</html>
Output of the above example:
Adding Element
Lion - Added node: FeedOn - Prey
Deer - Added node: FeedOn - Grass
animal has child nodes:true
data has child nodes:true
Comments
No comments have been made yet.
Please login to leave a comment. Login now