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>