首页 > 编程 > JavaScript > 正文

My first javascript file on xml.

2019-11-18 11:26:10
字体:
来源:转载
供稿:网友

<!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>

 



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表