<html>
<head>
<title>創建與添加節點</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<script language="javascript" type="text/javascript">
<!--
//加載XML文件的函數
function loadXML(xmlFile)
{
var _xmlDoc = null;
if(window.ActiveXObject)
{
_xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}
else
{
try
{
_xmlDoc = document.implementation.createDocument("","",null);
}
catch(ex)
{
alert(ex.message);
_xmlDoc = null;
}
}
if (_xmlDoc!=null)
{
_xmlDoc.async = false;
try
{
_xmlDoc.load(xmlFile);
}
catch(ex)
{
alert(ex.message);
_xmlDoc = null;
}
}
return _xmlDoc;
}
//遍歷XML文檔
function outText(_xmlDoc)
{
var _rootNode = _xmlDoc.documentElement;
var _itemNodes = _rootNode.childNodes;
for (i=0;i<_itemNodes.length;i++)
{
document.write("<br>");
var _attrNode = _itemNodes[i].getAttributeNode("id");
if (_attrNode!=null)
{
document.write("編號:",_attrNode.value,"<br>");
}
else
{
document.write("編號:無<br>");
}
var _childs = _itemNodes[i].childNodes;
for (j=0;j<_childs.length;j++)
{
if (_childs[j].nodeType==1)
{
document.write(_childs[j].nodeName,":",_childs[j].firstChild.nodeValue,"<br>");
}
else if (_childs[j].nodeType==8)
{
document.write("注釋:",_childs[j].nodeValue,"<br>");
}
}
}
}
//加載XML文件
var xmlDoc = loadXML("sample.xml");
if (xmlDoc!=null)
{
document.write("添加節點前的XML文檔內容。");
outText(xmlDoc);
//創建元素節點:
var itemNode = xmlDoc.createElement("Item");
var elePoemNode = xmlDoc.createElement("詩名");
var eleAuthorNode = xmlDoc.createElement("作者");
var eleContentNode = xmlDoc.createElement("內容");
//創建屬性節點:
var attrNode = xmlDoc.createAttribute("id");
//設置屬性節點的值
attrNode.nodeValue = "003";
//在<作者>節點上添加屬性
eleAuthorNode.setAttribute("字","子厚");
//創建文本節點:
var textPoemNode = xmlDoc.createTextNode("江雪");
var textAuthorNode = xmlDoc.createTextNode("柳宗元");
var textContentNode = xmlDoc.createTextNode("千山鳥飛絕,萬徑人蹤滅。孤舟蓑笠翁,獨釣寒江雪。");
//創建注釋節點:
var commentNode = xmlDoc.createComment("這是柳宗元被貶到永州之後寫的詩,借寒江獨釣的漁翁,抒發自己孤獨鬱悶的心情。");
//將屬性節點附加到<Item>節點上
itemNode.setAttributeNode(attrNode);
//將文本節點附加到元素節點上
elePoemNode.appendChild(textPoemNode);
eleAuthorNode.appendChild(textAuthorNode);
eleContentNode.appendChild(textContentNode);
//將<詩名>、<作者>、<內容>和注釋節點附加到<Item>節點上
itemNode.appendChild(elePoemNode);
itemNode.appendChild(eleAuthorNode);
itemNode.appendChild(commentNode);
itemNode.appendChild(eleContentNode);
//將<Item>節點添加到根節點上
xmlDoc.documentElement.appendChild(itemNode);
document.write("<br>添加節點後的XML文檔內容。");
outText(xmlDoc);
//輸出使用setAttributeNode()方法添加的屬性
var AuthorNode = xmlDoc.documentElement.childNodes[2].childNodes[1];
document.write(AuthorNode.firstChild.nodeValue,",字:",AuthorNode.getAttribute("字"));
}
else
{
alert("您的瀏覽不支持XML解析器或加載XML文件時出錯。");
}
-->
</script>
</head>
<body>
</body>
</html>