Search code examples
javaxmljaxp

How to replace an XML element with another (of another document)?


Here is my problem:

I have a source XML file that is parsed to a DOM. I also got an XML fragment (like: <a>text1<b/></a>). The "root" element of the fragment will always match with an element (same name) in the source DOM. Can I replace the DOM's node with this one?

First, thing I have thought of, is to parse the string fragment as a DOM. Then, I have tried to use replaceChild() method, but either I used it incorrectly or it can be applied only for nodes that already exist in the same DOM. So can someone show how can I achieve this?


Solution

  • You might need to call getParentNode() first, and then call replaceChild() against the parent node that you've got.