Remove Element from JDOM document using removeContent()

11,137

Solution 1

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.

Solution 2

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.

Share:
11,137
Swift-Tuttle
Author by

Swift-Tuttle

Updated on June 14, 2022

Comments

  • Swift-Tuttle
    Swift-Tuttle almost 2 years

    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.

  • Swift-Tuttle
    Swift-Tuttle about 13 years
    @dogbane Both these solutions seem to work and now I understand why it wasn't working earlier. Thanks a lot. I have to choose one solution so I might just go with this one, unless you guys think otherwise for some reason.
  • Florian Sesser
    Florian Sesser about 9 years
    el.detach() does el.getParent().removeContent(el); and is more readable.