Jumbala
Jumbala

Reputation: 4944

Removing a node from a XML File in Java

I have an XML file that is formatted like this:

<state>
  <image>
      <imageUrl>./testImages/testimage.png</imageUrl>
      <perspective id="0">
          <zoomLevel>1.0</zoomLevel>
          <offsetX>0.0</offsetX>
          <offsetY>0.0</offsetY>
      </perspective>
      <perspective id="1">
          <zoomLevel>1.0</zoomLevel>
          <offsetX>0.0</offsetX>
          <offsetY>0.0</offsetY>
      </perspective>
  </image>
</state>

In that file, I have multiple image nodes, but that is not the point. What I'd like is to be able to remove the < image > node (and all its child nodes)from the document.

I have the following code so far:

private void updateImageElement(Element image, Model model) throws SAXException, IOException, ParserConfigurationException{
    Element rootElement = doc.getDocumentElement();

    rootElement.removeChild(image);
    image.getParentNode().removeChild(image);
}

The "rootElement.removeChild(image);" line throws the following exception:

org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.

Which is weird, because if I print "rootElement", it displays "state", which IS image's parent node.

I then tried the following line ("image.getParentNode().removeChild(image)). This one doesn't throw an Exception, but nothing is removed either.

If I print that line, it also says the parent node is "state, so I can't even figure out what the difference between the two lines is.

Upvotes: 0

Views: 924

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234847

It sounds like you are working with two copies of the DOM for that document, and that doc is for one copy and image is from the other. You don't show the code that is responsible for setting doc and image, but you need to make sure that they are from the same node tree.

Upvotes: 2

Related Questions