<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Practice on Xml operation </TITLE>
</HEAD>
<BODY onload="addNewNode()">
</BODY>
</HTML>
<script>
function addNewNode()
{
var strNode = "<book>";
strNode = strNode + "<code>F5678</code>";
strNode = strNode + "</book>";
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
if(!xmlDoc.loadXML(strNode))
{
document.write("FAIL TO BUILD AN XML FILE");
}
else
{
document.write("<b>original xml file:</b>");
document.write("<xmp>" + xmlDoc.xml + "</xmp>");
//Add price node
var objNewNode = xmlDoc.createElement("price");
xmlDoc.documentElement.appendChild(objNewNode);
//Add the text of price node
var objNewText = xmlDoc.createTextNode("345");
var objNode = xmlDoc.documentElement.getElementsByTagName("price").item(0);
objNode.appendChild(objNewText);
document.write("<b>price node with text:</b>");
document.write("<xmp>"+xmlDoc.xml+"</xmp>");
//Add author node
var objPosNode = xmlDoc.documentElement.firstChild;
objNewNode = xmlDoc.createElement("author");
objNewText = xmlDoc.createTextNode("Calvin");
objNewNode.appendChild(objNewText);
xmlDoc.documentElement.insertBefore(objNewNode,objPosNode);
document.write("<b>author is added: </b>");
document.write("<xmp>" + xmlDoc.xml + "</xmp>");
//Add attribute into code node
objNode = xmlDoc.getElementsByTagName("code");
objNode.item(0).setAttribute("sales","Y");
document.write("<b>code's attribute is added: </b>");
document.write("<xmp>" + xmlDoc.xml + "</xmp>");
//Remove author node
var root = xmlDoc.documentElement;
var objDelNode = root.removeChild(root.getElementsByTagName("author").item(0));
document.write("<b>author node is deleted</b>");
document.write("<xmp>" + xmlDoc.xml + "</xmp>");
//Remove the attribute of code node
objNode = root.getElementsByTagName("code").item(0);
objNode.removeAttribute("sales");
document.write("<b>sales attribute of code node is removed:</b>");
document.write("<xmp>" + xmlDoc.xml + "</xmp>");
}
}
</script>