childNodes 属性返回指定节点的子节点的节点列表。
nodeObject.childNodes
提示:请使用节点列表的 length 属性来计算一个节点列表中节点的数目。当您已经知道节点列表的长度后,您就可以轻松地循环遍历此列表,并提取您所需要的值!
下面的代码片段使用 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>