2011-12-19 39 views
1

我有以下结构的XML文件:使用JDOM通过其属性删除元素?

<contacts> 
    <contact id="0"> 
     <firstname /> 
     <lastname /> 
     <address> 
      <street /> 
      <city /> 
      <state /> 
      <zip /> 
      <country /> 
     </address> 
     <phone /> 
     <email /> 
     <continfo> 
      <byemail /> 
      <byphone /> 
      <bymail /> 
     </continfo> 
     <comments /> 
     <datecreated /> 
    </contact> 
</contacts> 

使用JDOM,我想通过查找id属性删除整个接触元素及其所有的孩子。但是我很难解决这个问题。我已经尝试以下方法:

Element pageRoot = pageXML.getRootElement(); 

        List<Element> contacts = new ArrayList<Element>(pageRoot.getChildren()); 
        Element contact = null; 

        for(Element element : contacts){ 
         String att = element.getAttributeValue("id"); 
         if(Integer.parseInt(att) == id){ 
          contact = (Element) element.clone(); 
         } 
        } 
pageRoot.removeContent(contact); 

但是,该联系人永远不会被删除。如果任何人都能指出我的方向,那会很棒。谢谢。

回答

1

为什么要克隆元素?

您可以简单地直接将其删除:

if (...){ 
    elementToRemove = (Element) element; 
} 
... 
pageRoot.removeContent (elementToRemove); 
+0

适合你神......回想起来这也是非常愚蠢的我。谢谢。 – Cuthbert 2011-12-19 19:31:48

1

建议和(在我看来更容易)使用Iterator.remove()去除元素。您可以在遍历子元素时执行此操作,以避免将元素存储到额外的局部变量中。

List children = root.getChildren("foo"); 
Iterator itr = children.iterator(); 
while (itr.hasNext()) { 
    Element child = (Element) itr.next(); 
    String att = child.getAttributeValue("id"); 
    if(Integer.parseInt(att) == id){ 
    itr.remove(); 
    } 
} 

这个例子是从JDOM faq