javascript Xml增删改查(IE下)操作实现代码


<!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></div>
<input type="button" value="load" />
<input type="button" value="show" />
<input type="button" value="add" />
<input type="button" value="delete" />
<input type="button" value="update" />
<input type="button" value="query" />
</body>
</html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzydw.html