Java – a document error that occurs when a node is appended to XML
•
Java
public static Node createNodeFromXMLString(String xml) throws SAXException,IOException {
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's in the thread "main" org w3c. dom. Exception thrown in domexception: wrong_ DOCUMENT_ Err: the node is used in a document different from the document in which it was created 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)
Solution
Document. Importnode does not change the node it calls You should change this line:
document.importNode(node,true);
to
node = document.importNode(node,true);
Alternatively, use different variables:
Node importedNode = document.importNode(node,true); parent.appendChild(importedNode);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码