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

时间:2012-05-09 08:08:10

标签: 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);       
}

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

1 个答案:

答案 0 :(得分:21)

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

document.importNode(node,true);

node = document.importNode(node,true);

或者,使用其他变量:

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