语法错误?解析 XML 值时

Syntax Error? When parsing XML value

本文关键字:XML 值时 解析 错误 语法      更新时间:2023-09-26

我不知道我是否遇到语法错误,但编译器给了我

类型错误:"未定义"不是对象(评估 'xmlDoc.getElementsByTagName("icon")[count].childNodes')

是我在解析server XML时给我这个问题,我的实际 javascript 代码是这样的

var xmlDoc = Obj.responseXML;
var count = 0;
if(xmlDoc){
    while(count <= xmlDoc.getElementsByTagName("item").length){
    document.getElementById("flow").innerHTML += "<div class='item'><img class='content' src='" + xmlDoc.getElementsByTagName("icon")[count].childNodes[0].nodeValue.replace(/'s+$/g,' ') +"' /></div>";
    count++;
    }
       }else{
           alert("Unable to parse!");
       }

我的 XML 是这样的。

<feed>
<item>
<title>Given Title</title>
<icon>
http://i178.photobucket.com/albums/w255/ace003_album/Logo-ETC-RGB-e1353503652739.jpg
</icon>
</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
</feed>

我只想解析图像链接并显示它。DOM 解析器

 var url = "http://myURL.com/document.xml";
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          Obj = new XMLHttpRequest();
          }
        else
          {
          Obj = new ActiveXObject("Microsoft.XMLHTTP");
          }
        Obj.open("POST",url,false);
        Obj.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        Obj.send();

演示

首先,循环条件应该只是<而不是<=。通过使用后者,循环运行一次的次数过多,导致错误,因为索引超出范围。

其次,在 while 循环中,您将根据文档根目录的count获取icon元素。icon 是每个item的子项,因此您应该使用 item.getElementsByTagName('icon')[0] 而不是xmlDoc.getElementsByTagName('icon')[count] 来检索相对于itemicon

与问题无关,但将 HTML 构建为这样的字符串是不可取的。创建元素并将它们插入 DOM 会更好,因为您不需要处理任何转义。此外,在 while 之前存储对flow的引用,而不是在每次迭代时找到它。

var div;
var img;
var flow = document.getElementById('flow');
var items = xmlDoc.getElementsByTagName("item");
while(count < items.length){
    div = document.createElement('div');
    div.className = 'item';
    img = document.createElement('img');
    img.className = 'content';
    img.src = items[count].getElementsByTagName("icon")[0].childNodes[0].nodeValue.replace(/'s+$/g,' ');
    div.appendChild(img);
    flow.appendChild(div);
    count++;
}