最近使用了Javascript操作XML,積累了一些使用方法的語句,基本上能滿足平時的使用需要了。
但怕忘了,就記在這兒吧!
//創建一個DOM對象
var doc = new ActiveXObject(("Microsoft.XMLDOM");
//加載xml文件
doc.load("xxx.xml");
//加載xml字符集
doc.loadXML("<xml>");
//創建文件頭
var p = doc.createProcessingInstruction("xml","version='1.0'? encoding='gb2312'");
//添加節點
doc.appendChild(p);
//得到根接點
var root = doc.documentElement;
//兩種方式創建節點
var root = doc.createElement("node1");
var root = doc.createNode(1,"node1","");
//節點文本
node.text = " this is a test";
???
//創建屬性
var r = doc.createAttribute("id");
r.value="test";
//添加屬性
node.setAttributeNode(r1);
//修改屬性值
node.setAttribute("attr", "this is test")
//得到節點屬性
node.getAttribute("attr")
//刪除屬性
n.removeAttribute("class");
//添加文本節點
n.appendChild(doc.createTextNode("this is a text node."));
//添加注釋
n.appendChild(doc.createComment("this is a comment\n"));
???
//復制節點
var m = n.cloneNode(true);
//刪除節點
root.removeChild(node);
//創建數據段
var c = doc.createCDATASection("this is a cdata");
c.text = "hi,cdata";
//查找節點兩種方法
var a = doc.getElementsByTagName("ttyp");
var a = doc.selectNodes("http://root/node1/node2"); //注:“//root/node1/node2”是XPath的寫法,具體的使用請參考關于XPath的資料
var a = doc.selectSingleNode("http://root/node1/node2");
//顯示改節點的xml文本
a[i].xml
//節點的屬性集合
var attrs = node.attributes;
//查看屬性的名字和值
node.attributes[i].name
node.attributes[i].value
//XML保存(需要在服務端,客戶端用FSO)(注:這個我未使用過,姑且先寫在這。)
//doc.save();
???
//得到根接點XML
var root = node.ownerDocument
(注:改頁面會不斷更新,歡迎常來 ^_^)