2014-11-03 66 views
0

我想删除具有用户指定的特定名称属性的节点。我究竟做错了什么?让我们坐着用户输入:“猫”,并且每当系统发现具有属性cat的动物时,它就删除它。动物节点没有孩子。通过属性值删除节点的XML JavaScript

这是.xml文件

<animals> 
    <animal name="elephant"></animal> 
    <animal name="cat"></animal> 
    ...  
</animals> 

的简化这是我从删除XML文件中的特定节点的代码。

function delete() { 
    xmlDoc = loadXMLDoc("file.xml"); 
    root = xmlDoc.getElementsByTagName("animal"); 

    for (i = 0; i < root.length; i++) { 
     if (root[i].nodeType == 1) { 
      if (root[i].attributes[0].value == document.getElementById("del").value) { 
       xmlDoc.removeChild(root[i]); 
       display(); // function displaying the results 
      } 
     } 
    } 
} 
+0

函数中的局部变量应该用'var'声明。 – Pointy 2014-11-03 16:44:38

回答

2

<animal>节点不在XML DOM顶级节点的孩子,所以xmlDoc.removeChild()将无法​​正常工作。

root[i].parentNode.removeChild(root[i]); 

这就是说,你可能会遇到困难,由于该节点列表从getElementsByTagName()返回的事实是现场。当你删除元素时,列表会缩小,你会跳过一些。你可以改变循环来处理:

for (var i=0; i<root.length;) { 
    if(root[i].nodeType==1 && root[i].attributes[0].value==document.getElementById("del").value) { 
     xmlDoc.removeChild(root[i]); 
     display(); // function displaying the results 
    } 
    else 
     i++; 
}