Remove Element from JDOM document using removeContent()

Swift-Tuttle picture Swift-Tuttle · Apr 12, 2011 · Viewed 10.8k times · Source

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.

Answer

forty-two picture forty-two · Apr 12, 2011

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.