0

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?

user2089117
  • 3
  • 1
  • 3

2 Answers2

2

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

wonhee
  • 1,581
  • 1
  • 14
  • 24
  • Thanks, you were right! I have misunderstood the API and tried to applied the method on document root. Now works as expected. Also, I had to use importNode() in order to get a fragment from another document to the desired. – user2089117 Feb 20 '13 at 20:48
0
//Importing template node to the target document(this solves wrong_DOCUMENT_ERR:)   
Node importedTemplateChildNode = targetDoc.importNode(templateChildNode, true);

// Replace target child node with the template node
targetParentNode.replaceChild(importedTemplateChildNode, targetChildnode);       

Transformer tranFac = TransformerFactory.newInstance().newTransformer();
tranFac.transform(new DOMSource(targetDoc), new StreamResult(new FileWriter(targetXmlFile))); 
mszymborski
  • 1,615
  • 1
  • 20
  • 28