DOM 遍历
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