This is my xml document:
<definitions>
<task name="TASK1"
class="CLASS"
group="GROUP">
<trigger count="3" interval="400"/>
<property xmlns:task="URI"
name="PROPERTY2"
value="VALUE1"/>
<property xmlns:task="URI"
name="PROPERTY2"
value="VALUE2"/>
</task>
<task name="TASK1"
class="CLASS"
group="GROUP">
<trigger count="1" interval="600"/>
<property xmlns:task="URI"
name="PROPERTY2"
value="VALUE1"/>
<property xmlns:task="URI"
name="PROPERTY2"
value="VALUE2"/>
</task>
<another_tag name="a_name"/>
<another_tag2 name="a_name2"/>
<another_tag3> something in the middle </another_tag3>
</definitions>
I have to delete all <task> tags and what inside them. I used this java code:
Document esb = new Document();
SAXBuilder saxBuilder = new SAXBuilder();
try {
esb = saxBuilder.build(new File("C:\\...path\\file.xml"));
}
catch (JDOMException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
Element root = esb.getRootElement();
boolean b = root.removeChild("task");
System.out.println(b);
I can't understand how to obtain an xml file without <task> tag and containing only <another_tag> tag. I've looked for other solutions but nothing useful. I also used removeContent() method, but nothing. I imported jdom2 libraries, I need to use recent libraries, because there are bad interactions among jdom and jdom2, so I would prefer to use recent libraries only. Any suggest about how to remove some element from this xml CODE?
The api says this for the function 'removeChild': ... This removes the first child element (one level deep) with the given local name and belonging to no namespace...
The removeChild function removes only one child. So if you want remove all childs with a specific name you need to use a loop. If the function call can't find a node with the desired name it returns with false.
If I work with your sample xml the third call of removeChild returns with false. So the following code will delete all task childs
...
boolean b = root.removeChild("task");
while (b)
b = root.removeChild("task");
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With