请问一下用JS遍历子节点的问题
<bookstore>
<book category= "WEB ">
<title lang= "en "> XQuery Kick Start </title>
<author> James McGovern </author>
<year> 2003 </year>
<price> 49.99 </price>
</book>
<book category= "WEB ">
<title lang= "en "> Learning XML </title>
<author> Erik T. Ray </author>
<year> 2003 </year>
<price> 39.95 </price>
</book>
</bookstore>
如果我现在用
var x=xmlDoc.getElementsByTagName( "book ");
定义以后该怎么样获得所有子节点呢?
for(i=0;i <x.length;i++)
{
alert(x[i].childNodes[0].childNodes[0]nodeValue);
}
我现在是这样写的,但是不行
可以假设的是book下的子节点的Name都是不可知的
[解决办法]
<script language= "javascript ">
var xmlDom=new ActiveXObject( "MSXML2.DOMDocument.3.0 ");
xmlDom.async= "false ";
xmlDom.load( "test.xml ");
var x=xmlDom.getElementsByTagName( "book ");
for(var i=0;i <x.length;i++)
{
document.write( "| +-- "+x.item(i).nodeName+ " <br/> ");
if(x.item(i).hasChildNodes)
{
xmlSubNode=x.item(i).childNodes;
for(var j=0;j <xmlSubNode.length;j++)
{
document.write( "| | +-- ");
document.write(xmlSubNode.item(j).nodeName+ ": ");
document.write(xmlSubNode.item(j).text+ " <br/> ");
}
}
}
</script>
测试通过!
[解决办法]
var x=xmlDom.getElementsByTagName( "book ");
for(var i=0;i <x.length;i++)
{
document.write( "| +-- "+x.item(i).nodeName+ " <br/> ");
if(x.item(i).hasChildNodes)
{
xmlSubNode=x.item(i).childNodes;
for(var j=0;j <xmlSubNode.length;j++)
{
if(xmlSubNode.item(j).nodeType!=1) continue; //*不是element的过滤掉
document.write( "| | +-- ");
document.write(xmlSubNode.item(j).nodeName+ ": ");
if (window.ActiveXObject)
document.write(xmlSubNode.item(j).text+ " <br/> ");
else
document.write(xmlSubNode.item(j).textContent+ " <br/> ");
}
}
}