java 在 xml 中附加节点时出现错误的文档错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10512183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:22:13  来源:igfitidea点击:

Wrong document error while appending a node in xml

javaxml

提问by kannanrbk

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)

它在线程“main”org.w3c.dom.DOMException 中抛出异常:WRONG_DOCUMENT_ERR:节点在与创建它的文档不同的文档中使用。在 org.apache.xerces.dom.ParentNode.internalInsertBefore(Unknown Source) 在 org.apache.xerces.dom.ParentNode.insertBefore(Unknown Source) 在 org.apache.xerces.dom.NodeImpl.appendChild(Unknown Source)

回答by Jon Skeet

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

Document.importNode不会改变它被调用的节点。你应该改变这一行:

document.importNode(node,true);

to

node = document.importNode(node,true);

Alternatively, use a different variable:

或者,使用不同的变量:

Node importedNode = document.importNode(node, true);
parent.appendChild(importedNode);