childNodes 属性返回文档的子节点的节点列表。
documentObject.childNodes
提示:请使用 NodeList 的长度属性来测定节点列表中的节点数量。在您知道节点列表的长度后,就能够轻易地循环遍历此节点列表,并提取您需要的值!
下面的代码片段使用 loadXMLDoc() 把 "books.xml" 载入 xmlDoc 中,并显示 XML 文档的子节点:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.childNodes;
for (i=0;i<x.length;i++)
{
document.write("Nodename: " + x[i].nodeName);
document.write(" (nodetype: " + x[i].nodeType + ")
");
}
输出 IE:
Nodename: xml (nodetype: 7)
Nodename: #comment (nodetype: 8)
Nodename: bookstore (nodetype: 1)
输出 Mozilla (Firefox):
Nodename: #comment (nodetype: 8)
Nodename: bookstore (nodetype: 1)
显示 XML 文档中所有元素的所有子节点
<!DOCTYPE html> <html> <head> <script src="loadxmldoc.js"> </script> </head> <body> <script> xmlDoc=loadXMLDoc("books.xml"); document.write("Nodename: " + xmlDoc.nodeName); document.write(" (nodetype: " + xmlDoc.nodeType + ")<br>"); x=xmlDoc.documentElement; document.write("Nodename: " + x.nodeName); document.write(" (nodetype: " + x.nodeType + ")<br>"); y=x.childNodes; for (i=0;i<y.length;i++) { document.write("Nodename: " + y[i].nodeName); document.write(" (nodetype: " + y[i].nodeType + ")<br>"); for (z=0;z<y[i].childNodes.length;z++) { document.write("Nodename: " + y[i].childNodes[z].nodeName); document.write(" (nodetype: " + y[i].childNodes[z].nodeType + ")<br>"); } } </script> </body> </html>