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.
Why do you clone the Element?
You can simply remove it directly: