Question

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?

Was it helpful?

Solution

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

OTHER TIPS

//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))); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top