I want to replace a existing Dom node with a new node I have created.I am implementing this as
String messageBody=" <imgGroup><img src="src" width="width" height="height" alt="alt" type="type" orient="orient"/></imgGroup>"
File file=new File("doc.xml");
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
doc = docBuilder.parse(file);
Element node = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream(messageBody.getBytes()))
.getDocumentElement();
System.out.println(node.getClass());
doc.getDocumentElement().replaceChild((Node)node, doc.getDocumentElement().getFirstChild());
}catch(Exception e){
e.printStackTrace();
}
I am getting an run time error
WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.
Can any one suggest how to do it in different way?
You need to adopt the node by the new document, calling
Document.adoptNode(). Note thatadoptNode()in itself won’t add the node anywhere in the target document, just allow you to add it to the DOM tree. You still have to callreplaceChild()afterwards.