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

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top