html文件: 复制代码 代码如下: js操作Xml增删改查(IE下) <!-- <BR>/*等解决的问题: <BR>1.xpath到底是定位到哪一层,怎样定位到比如root这一级还是person或name这一级. <BR>*/ <BR>var xmlDoc; <BR>var rootNode; //根结点 <BR>//装载Xml文档 <BR>function loadXml(){ <BR>try{ <BR>xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); <BR>xmlDoc.async=false;//关闭异步加载 <BR>xmlDoc.load("XmlFile.xml");//load是从文件,loadXML是从字符串. <BR>rootNode = xmlDoc.documentElement; <BR>}catch(e) {alert(e.message)} <BR>} <BR>//显示内存中的Xml文档 <BR>function outXml(){ <BR>var divXml=document.getElementById("divXml"); <BR>divXml.innerHTML=xmlDoc.xml;//显示xml内容,技巧是加个xml后缀.? <BR>alert(xmlDoc.xml); <BR>} <BR>//增 <BR>function addXml(){ <BR>//叶子结点,设置text值 <BR>var newName = xmlDoc.createElement("name"); <BR>newName.text = "crane"; <BR>var newGender = xmlDoc.createElement("gender"); <BR>newGender.text = "female"; <BR>//父级结点,用appendChild(childNode); <BR>var newPerson = xmlDoc.createElement("person"); <BR>//设置属性id <BR>newPerson.setAttribute("id","2"); <BR>newPerson.appendChild(newName); <BR>newPerson.appendChild(newGender); <BR>//增加到根结点 <BR>rootNode.appendChild(newPerson); <BR>alert(xmlDoc.xml); <BR>} <BR>//删 <BR>function deleteXml(){ <BR>//先找到结点 <BR>var singleNode = xmlDoc.selectSingleNode("/root/person[name='tree']"); <BR>//找到父级再删除 <BR>singleNode.parentNode.removeChild(singleNode); <BR>alert(xmlDoc.xml); <BR>} <BR>//改 <BR>function updateXml(){ <BR>var singleNode = xmlDoc.selectSingleNode("/root/person[name='crane']"); <BR>singleNode.childNodes[0].text = "updated"; <BR>alert(xmlDoc.xml); <BR>} <BR>//查 <BR>function queryXml(){ <BR>//alert(rootNode.nodeName);//节点名 <BR>//alert(rootNode.text);//节点里的全部内容 <BR>//xPath选择节点数组 <BR>//var nodes = xmlDoc.selectNodes("/root/person"); <BR>//alert(nodes[0].text); <BR>//选择单个节点 <BR>/*总结 <BR>1."/root/person[name='tree']"等同于"/root[person/name='tree']"即找出来的是person结点 <BR>*/ <BR>var singleNode = xmlDoc.selectSingleNode("/root/person[gender='female']");//这里的值需要加引号 <BR>alert(singleNode.text); <BR>alert(singleNode.getAttribute("id")); <BR>//测试xpath定位 <BR>var sglNode = xmlDoc.selectSingleNode("/root[person/gender='male']");//这里定位不明确.再研究. <BR>alert(sglNode.text); <BR>//显示全部xml文档 <BR>//alert(xmlDoc.xml); <BR>} <BR>// --> Xml文件: 复制代码 代码如下: tree male