Reputation: 485
Given the following scenario, where the xml, Geography.xml looks like -
<Geography xmlns:ns="some valid namespace">
<Country>
<Region>
<State>
<City>
<Name></Name>
<Population></Population>
</City>
</State>
</Region>
</Country>
</Geography>
and the following sample java code -
InputStream is = new FileInputStream("C:\\Geography.xml");
SAXBuilder saxBuilder = new SAXBuilder();
Document doc = saxBuilder.build(is);
XPath xpath = XPath.newInstance("/*/Country/Region/State/City");
Element el = (Element) xpath.selectSingleNode(doc);
boolean b = doc.removeContent(el);
The removeContent()
method doesn't remove the Element City
from the content list of the doc
. The value of b is false
I don't understand why is it not removing the Element, I even tried to delete the Name
& Population
elements from the xml just to see if that was the issue but apparently its not.
Another way I tried, I don't know why I know its not essentially different, still just for the sake, was to use Parent
-
Parent p = el.getParent();
boolean s = p.removeContent(new Element("City"));
What might the problem? and a possible solution? and if anyone can share the real behaviour of the method removeContent()
, I suspect it has to do with the parent-child relationship.
Upvotes: 4
Views: 12133
Reputation: 1909
This way works keeping in mind that .getParent() returns a Parent object instead of an Element object, and the detach() method which eliminates the actual node, must be called from an Element.
Instead do:
el.getParentElement().detach();
This will remove the parent element with all it's children !
Upvotes: 0
Reputation: 274778
If you want to remove the City
element, get its parent and call removeContent
:
XPath xpath = XPath.newInstance("/*/Country/Region/State/City");
Element el = (Element) xpath.selectSingleNode(doc);
el.getParent().removeContent(el);
The reason why doc.removeContent(el)
does not work is because el
is not a child of doc
.
Check the javadocs for details. There are a number of overloaded removeContent
methods there.
Upvotes: 4
Reputation: 12817
Sure, removeContent(Content child)
removes child if child belongs to the parents immediate children, which it does not in your case. Use el.detach()
instead.
Upvotes: 5