Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong document error while appending a node in xml

Tags:

java

xml

public static Node createNodeFromXMLString(String xml) throws SAXException,
        IOException {
    return builder.parse(new ByteArrayInputStream(xml.getBytes()))
            .getDocumentElement();
}


public static void main(String args[]){
   Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("server.xml");
   XPath xpath = XPathFactory.newInstance().newXPath();
   Node element = (Node)xpath.evaluate("/Server/Service/Connector[2]",document,XPathConstants.NODE);
   String newNode = nodeToString(element).replace("port=\"8443\"", "port=\"8453\"");
   Node parent = element.getParentNode();
   Node node = createNodeFromXMLString(newNode);
   parent.removeChild(element);
   document.importNode(node,true);
   parent.appendChild(node);       
}

It throws Exception in thread "main" org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it. at org.apache.xerces.dom.ParentNode.internalInsertBefore(Unknown Source) at org.apache.xerces.dom.ParentNode.insertBefore(Unknown Source) at org.apache.xerces.dom.NodeImpl.appendChild(Unknown Source)

like image 518
kannanrbk Avatar asked Nov 29 '22 02:11

kannanrbk


1 Answers

Document.importNode doesn't change the node it's called on. You should change this line:

document.importNode(node,true);

to

node = document.importNode(node,true);

Alternatively, use a different variable:

Node importedNode = document.importNode(node, true);
parent.appendChild(importedNode);
like image 143
Jon Skeet Avatar answered Dec 04 '22 15:12

Jon Skeet