代碼如下:
<script language="JavaScript">
<!--
var doc = new ActiveXObject("Msxml2.DOMDocument"); //ie5.5+,CreateObject("Microsoft.XMLDOM")
//加載文檔
//doc.load("b.xml");
//創(chuàng)建文件頭
var p = doc.createProcessingInstruction("xml","version='1.0' encoding='gb2312'");
//添加文件頭
doc.appendChild(p);
//用于直接加載時(shí)獲得根接點(diǎn)
//var root = doc.documentElement;
//兩種方式創(chuàng)建根接點(diǎn)
// var root = doc.createElement("students");
var root = doc.createNode(1,"students","");
//創(chuàng)建子接點(diǎn)
var n = doc.createNode(1,"ttyp","");
//指定子接點(diǎn)文本
//n.text = " this is a test";
//創(chuàng)建孫接點(diǎn)
var o = doc.createElement("sex");
o.text = "男"; //指定其文本
//創(chuàng)建屬性
var r = doc.createAttribute("id");
r.value="test";
//添加屬性
n.setAttributeNode(r);
//創(chuàng)建第二個(gè)屬性
var r1 = doc.createAttribute("class");
r1.value="tt";
//添加屬性
n.setAttributeNode(r1);
//刪除第二個(gè)屬性
n.removeAttribute("class");
//添加孫接點(diǎn)
n.appendChild(o);
//添加文本接點(diǎn)
n.appendChild(doc.createTextNode("this is a text node."));
//添加注釋
n.appendChild(doc.createComment("this is a comment\n"));
//添加子接點(diǎn)
root.appendChild(n);
//復(fù)制接點(diǎn)
var m = n.cloneNode(true);
root.appendChild(m);
//刪除接點(diǎn)
root.removeChild(root.childNodes(0));
//創(chuàng)建數(shù)據(jù)段
var c = doc.createCDATASection("this is a cdata");
c.text = "hi,cdata";
//添加數(shù)據(jù)段
root.appendChild(c);
//添加根接點(diǎn)
doc.appendChild(root);
//查找接點(diǎn)
var a = doc.getElementsByTagName("ttyp");
//var a = doc.selectNodes("http://ttyp");
//顯示改接點(diǎn)的屬性
for(var i= 0;i<a.length;i++)
{
alert(a[i].xml);
for(var j=0;j<a[i].attributes.length;j++)
{
alert(a[i].attributes[j].name);
}
}
//修改節(jié)點(diǎn),利用XPATH定位節(jié)點(diǎn)
var b = doc.selectSingleNode("http://ttyp/sex");
b.text = "女";
//alert(doc.xml);
//XML保存(需要在服務(wù)端,客戶端用FSO)
//doc.save();
//查看根接點(diǎn)XML
if(n)
{
alert(n.ownerDocument.xml);
}
//-->
</script>
更多信息請(qǐng)查看IT技術(shù)專欄