我正在使用一个函数,它接收两个DOM元素 - 来自不同文档的父元素和子元素。我导入子元素,转换它,然后将它附加到父元素。但是,以下代码中的最后一行是抛出一个dom异常:org.w3c.dom.DOMException:WRONG_DOCUMENT_ERR:节点用于与创建它的文档不同的文档中。
请参阅下面的代码:
public void attachNodeToParent (Element parent, Element child) throws Exception {
Document parent_doc = parent.getOwnerDocument();
child = (Element)parent_doc.importNode(child, true);
// Imported child Element is shown below:
// <node id="101">
// <node id="102">
// <node id="103" />
// </node>
// <node id="104">
// <node id="103" />
// </node>
// </node>
// convert child Element into String
Source source = new DOMSource(child);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
String childXml = stringWriter.getBuffer().toString();
// Recursively modify the id attributes of every node
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(childXml)));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
NodeList nodes = (NodeList) xpath.compile("//node[@id]").evaluate(doc, XPathConstants.NODESET);
for (int nodeNumber = 0; nodeNumber < nodes.getLength(); ++nodeNumber) {
final Element node = (Element) nodes.item(nodeNumber);
final String nodeId = node.getAttribute("id");
final String newNodeId = "prefix/" + nodeId;
node.getAttributeNode("id").setValue(newNodeId);
}
final StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
writer.flush();
writer.close();
String transformedChildXml = writer.toString();
// Prase transformedChildXml String into XML
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(transformedChildXml)));
document.setXmlStandalone(false);
child = document.getDocumentElement();
// child Element is now transformed to:
// <node id="prefix/101">
// <node id="prefix/102">
// <node id="prefix/103" />
// </node>
// <node id="prefix/104">
// <node id="prefix/103" />
// </node>
// </node>
// append transformed child Element to parent Element
// Throws o rg.w3c.dom.DOMException: WRONG_DOCUMENT_ERR:
// A node is used in a different document than the one that created it.
parent.appendChild(child);
}
答案 0 :(得分:0)
简短的回答是倒数第二行的子元素属于由行
创建的文档Document document = builder.parse(new InputSource(new StringReader(transformedChildXml)));
而不是父母的所有者文件。因此,您必须再次使用importNode将其传输到目标文档。
但不要这样做。您的代码有两个序列化为String并解析回Document循环,这是非常低效的,也不是必需的。一旦你在开始时调用了importNode,只需将id固定到位,然后将子节点附加到父节点。