0

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.

2
  • Can you produce a short but complete program (ideally a console app) which demonstrates the problem? Commented Dec 12, 2012 at 16:20
  • @Jon Skeet I'll keep that in mind next time, I thought this snippet was enough to show the problem, but Ted Hopp's answer proved otherwise since my error wasn't in it. Thanks anyway! Commented Dec 12, 2012 at 16:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You are correct. I forgot to change the reference back to the same document after some testing. Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.