Posted in Javascript onJanuary 30, 2009
html文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>js操作Xml增删改查(IE下)</title> <script type="text/javascript"><!-- /*等解决的问题: 1.xpath到底是定位到哪一层,怎样定位到比如root这一级还是person或name这一级. */ var xmlDoc; var rootNode; //根结点 //装载Xml文档 function loadXml(){ try{ xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false;//关闭异步加载 xmlDoc.load("XmlFile.xml");//load是从文件,loadXML是从字符串. rootNode = xmlDoc.documentElement; }catch(e) {alert(e.message)} } //显示内存中的Xml文档 function outXml(){ var divXml=document.getElementById("divXml"); divXml.innerHTML=xmlDoc.xml;//显示xml内容,技巧是加个xml后缀.? alert(xmlDoc.xml); } //增 function addXml(){ //叶子结点,设置text值 var newName = xmlDoc.createElement("name"); newName.text = "crane"; var newGender = xmlDoc.createElement("gender"); newGender.text = "female"; //父级结点,用appendChild(childNode); var newPerson = xmlDoc.createElement("person"); //设置属性id newPerson.setAttribute("id","2"); newPerson.appendChild(newName); newPerson.appendChild(newGender); //增加到根结点 rootNode.appendChild(newPerson); alert(xmlDoc.xml); } //删 function deleteXml(){ //先找到结点 var singleNode = xmlDoc.selectSingleNode("/root/person[name='tree']"); //找到父级再删除 singleNode.parentNode.removeChild(singleNode); alert(xmlDoc.xml); } //改 function updateXml(){ var singleNode = xmlDoc.selectSingleNode("/root/person[name='crane']"); singleNode.childNodes[0].text = "updated"; alert(xmlDoc.xml); } //查 function queryXml(){ //alert(rootNode.nodeName);//节点名 //alert(rootNode.text);//节点里的全部内容 //xPath选择节点数组 //var nodes = xmlDoc.selectNodes("/root/person"); //alert(nodes[0].text); //选择单个节点 /*总结 1."/root/person[name='tree']"等同于"/root[person/name='tree']"即找出来的是person结点 */ var singleNode = xmlDoc.selectSingleNode("/root/person[gender='female']");//这里的值需要加引号 alert(singleNode.text); alert(singleNode.getAttribute("id")); //测试xpath定位 var sglNode = xmlDoc.selectSingleNode("/root[person/gender='male']");//这里定位不明确.再研究. alert(sglNode.text); //显示全部xml文档 //alert(xmlDoc.xml); } // --></script> </head> <body> <div id="divXml"></div> <input type="button" value="load" onclick="loadXml();" /> <input type="button" value="show" onclick="outXml();" /> <input type="button" value="add" onclick="addXml();" /> <input type="button" value="delete" onclick="deleteXml();" /> <input type="button" value="update" onclick="updateXml();" /> <input type="button" value="query" onclick="queryXml();" /> </body> </html>
Xml文件:
<?xml version="1.0" encoding="utf-8" ?> <root> <person id="1"> <name>tree</name> <gender>male</gender> </person> </root>
javascript Xml增删改查(IE下)操作实现代码
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@