XML DOM – 遍歷節點樹
遍歷(Traverse)意味著在節點樹中進行循環或移動。
遍歷節點樹
通常您想要循環XML 文檔,比如:當您需要提取每個元素的值時。
這叫做"遍歷節點樹"。
下面的實例遍歷<book> 的所有子節點,並顯示他們的名稱和值:
實例
<html>
<head>
<script src="loadxmlstring.js"></script>
</head>
<body>
<script>
text="<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
xmlDoc=loadXMLString(text);
// documentElement always represents the root node
x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("
");
}
</script>
</body>
</html>
<head>
<script src="loadxmlstring.js"></script>
</head>
<body>
<script>
text="<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
xmlDoc=loadXMLString(text);
// documentElement always represents the root node
x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("
");
}
</script>
</body>
</html>
輸出:
title: Everyday Italian
author: Giada De Laurentiis
year: 2005
author: Giada De Laurentiis
year: 2005
嘗試一下»
實例解釋:
- loadXMLString()把XML字符串載入xmlDoc中
- 獲取根元素的子節點
- 輸出每個子節點的節點名稱以及文本節點的節點值