使用Javascript从XML到Html解析错误

时间:2022-12-01 13:11:06

i am getting data from XML file and show it into HTML file the XML files contains sub-sub-child of nodes My XML Files

我从XML文件中获取数据并将其显示到HTML文件中,XML文件包含节点My XML Files的子子子

<?xml version="1.0" encoding="utf-8"?>
<projects>
<project title="title1" subtitle="subtitle1">
    <text>First Tesxt</text>
    <images>
        <image url="1/176.png"></image>
        <image url="1/178.png"></image>
        <image url="1/173.png"></image>
    </images>
</project>
<project title="title2" subtitle="subtitle2">
    <text>Second Test</text>
    <images>
        <image url="2/164.png"></image>
        <image url="2/175.png"></image>
        <image url="2/1767.png"></image>
    </images>
</project>

The HTML Javascript Part is

HTML Javascript部分是

<html>
<head>
</head>
<body>
<script>
function loadXMLDoc(dname) 
{
    if (window.XMLHttpRequest)
    {
        xhttp=new XMLHttpRequest();
    }
    else
    {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET",dname,false);
    xhttp.send();
    return xhttp.responseXML;
}
xmlDoc=loadXMLDoc("projects.xml");

var length = xmlDoc.getElementsByTagName("project").length;
for(i=0; i<length;i++)
{
    alert(xmlDoc.getElementsByTagName("project")[i].getAttribute("title"));
    alert(xmlDoc.getElementsByTagName("project")[i].getAttribute("subtitle"));
    alert(xmlDoc.getElementsByTagName("text")[i].childNodes[0].nodeValue);
    var lengthImage = xmlDoc.getElementsByTagName("images")[i].childNodes[0].length;
    for(var j=0; j<lengthImage; j++)
    {
        alert(xmlDoc.getElementsByTagName("image")[j].getAttribute("url"));
    }
}
</script>
</body>
</html>

But the images node cannot display correctly it always iterates 4 time in loop

但是图像节点无法正确显示它总是在循环中迭代4次

1 个解决方案

#1


0  

1 - Your XML doesn't have </projects> on the last line.
2 - var lengthImage = xmlDoc.getElementsByTagName("images")[i].childNodes.length; //childNodes does't need "[0]"

1 - 您的XML在最后一行没有 。 2 - var lengthImage = xmlDoc.getElementsByTagName(“images”)[i] .childNodes.length; // childNodes不需要“[0]”

#1


0  

1 - Your XML doesn't have </projects> on the last line.
2 - var lengthImage = xmlDoc.getElementsByTagName("images")[i].childNodes.length; //childNodes does't need "[0]"

1 - 您的XML在最后一行没有 。 2 - var lengthImage = xmlDoc.getElementsByTagName(“images”)[i] .childNodes.length; // childNodes不需要“[0]”