Cuthbert
Cuthbert

Reputation: 2998

Use JDOM to remove an element by its attribute?

I have an XML file with the following structure:

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

Using JDOM, I'd like to remove an entire contact element and all of its children by looking up the id attribute. But I'm having some trouble figuring this out. I've tried the following:

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); 

Yet that contact never gets removed. If anyone could point me in a direction, that would be great. Thank you.

Upvotes: 1

Views: 3281

Answers (2)

Stephan
Stephan

Reputation: 4443

It is recommended and (in my opinion easier) to use Iterator.remove() for removing elements. You can do this while iterating through the children to avoid storing the element to an extra local variable.

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();
  }
}

This example is adapted from the JDOM faq

Upvotes: 1

scravy
scravy

Reputation: 12283

Why do you clone the Element?

You can simply remove it directly:

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

Upvotes: 1

Related Questions