1

我在从文档中删除 XML 元素时遇到问题。我已经搜索了论坛,我认为我做的事情是正确的,请你能帮我弄清楚我在哪里搞砸了吗?

我有一个包含我正在循环的 ID 的数组。在该循环中,我循环遍历 XML 文档以查找“myId”属性与数组中的 ID 相同的元素。当我找到一个我想从 XML 文档中删除该元素时。

这是我的代码:

var xmlFilename=document.getElementById('xmlFilename').value;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }

    xmlhttp.open("GET",xmlFilename,false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;

    // lets get all the xml elements into xAll
    var xAll=xmlDoc.getElementsByTagName('*');
    // lets use the buttonList array - this corresponds to the elements in the xml to hide

    for (var i=0; i<buttonList.length;i++) {
        alert ("Looking for "+buttonList[i]);
        //find the XML node with the same id
        for(var j=0;j<xAll.length;j++) {
            y=xAll[j];
            if (y.getAttribute('myId')==buttonList[i]) {
                alert('Found a match');
                xmlDoc.documentElement.removeChild(y);
                alert('removed');
            } 
        }
        alert('next!');
    }
    alert('all done');

它按预期循环,但是当它找到匹配项时 xmlDoc.documentElement.removeChild(y); 行导致脚本失败,并且永远不会进入“已删除”状态。

我很感激任何正确方向的帮助/指示。

谢谢,马克

4

2 回答 2

0

getElementsByTagName可以在 DOM 树的所有级别找到元素,而不仅仅是文档元素的直接子元素。与其尝试y.documentElement _ y_

于 2012-11-09T12:15:27.293 回答
0

尝试:

var i = 0, j, y;
for (; i < buttonList.length; i += 1) {
  // Running "backwards" is done on purpose, as `xAll` is a "live" NodeList.
  // If otherwise, you'd run into problems regarding wrong indexes. 
  for(j = xAll.length - 1; j >= 0; j -= 1) {
    y = xAll[j];
    if (y.getAttribute('myId') == buttonList[i]) {
      y.parentNode.removeChild(y);
    } 
  }
}
于 2012-11-09T12:30:37.957 回答