XML: JDOM: removing all elements with certain attribute

C

cyberco

Using JDOM I want to remove all elements with attribute uid="x" from
the following xml:


=======================================
<root>
<ele>
<sub uid="x">
bla
</sub>
</ele>
<ele uid="x">
boe
</ele>
</root>

=======================================

How can I do that? Iterating and removing at the same time gives me
concurrent modification exceptions.

2B
 
C

cyberco

Using XPath seemed to be the easiest way:

==================================================================
Document doc = new SAXBuilder().build(new StringReader(xml));
List<Element> Eles = XPath.selectNodes(doc.getRootElement(), "//
*[@uid='x']");
for (Element e: Eles) {
e.getParentElement().removeContent(e);
}

//optionally print it
System.out.println(new XMLOutputter().outputString(doc));
==================================================================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,206
Latest member
SybilSchil

Latest Threads

Top