0

My xml file is like:

it contains different 'object' nodes and in different objects there are different parameters one is deleted parameter.

I want to delete the all 'object' nodes that contains the deleted parameter 1.

This is the code that deletes the node object which has a parameter node deleted =1:

x=xmlDoc.documentElement;
for(var count=0; count<5;count++){
  var y=x.getElementsByTagName("deleted")[count]; //Find that nodes arent
  if(y.textContent == "1") {
    var z=y.parentNode; //delete the node from the parent.
    x.removeChild(z);
    Xml2String1= new XMLSerializer().serializeToString(x);
  }
}
4

1 回答 1

0

您的循环不正确:

for(var x1=0; x1<5;x1++){
  var y=x.getElementsByTagName("deleted")[x1];

您的循环运行 5 次迭代,而不考虑找到的<deleted>元素数量。每次通过循环时,您都会再次搜索并获得剩余元素的新NodeList/HTMLCollection<deleted>,但无论如何,您的循环计数器都会增加。

试试这个:

var deletedNodesList = x.getElementsByTagName("deleted");
var nodesToDelete = [];
for (var index = 0; index < deletedNodes.length ; index += 1)
    {
    var node = deletedNodes[index];
    if (node.textContent == "1")
        {
        nodesToDelete.push( node.parentNode ); //delete the node from the parent
        }
    }

nodesToDelete.forEach( function() { x.removeChild(this); } );

请注意,根据 MDN 上的文档,NodeList 是一个实时集合,因此在处理它时不要修改它。


PS。我赞同 raam86 的建议,即使用健全(有意义)的变量名。有意义的变量名使代码更容易理解,从而更容易编写正确的代码并解决错误代码中的问题。

于 2013-07-12T19:30:06.417 回答