19

我有一个Node从一个Document。我想把Node它变成一个新的根节点Document

我能想到的唯一方法是:

Node node = someChildNodeFromDifferentDocument;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);

DocumentBuilder builder = factory.newDocumentBuilder();

Document newDocument = builder.newDocument();
newDocument.importNode(node);
newDocument.appendChild(node);

这行得通,但我觉得它相当烦人。有没有我没有看到的更简洁/更直接的方式,还是我必须这样做?

4

5 回答 5

21

该代码对我不起作用-但是通过对此相关问题的一些更改,我可以使其工作如下:

Node node = someChildNodeFromDifferentDocument;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document newDocument = builder.newDocument();
Node importedNode = newDocument.importNode(node, true);
newDocument.appendChild(importedNode);
于 2013-01-14T08:39:03.400 回答
6

That looks about right to me. While it does look generally verbose, it certainly doesn't look significantly more verbose than other code using the DOM API. It's just an annoying API, unfortunately.

Of course, it's simpler if you've already got a DocumentBuilder from elsewhere - that would get rid of quite a lot of your code.

于 2012-11-08T18:10:39.013 回答
2

来自节点的文档

Document document = node.getOwnerDocument();
于 2020-01-28T08:19:31.443 回答
0

您可以简单地使用克隆旧文档cloneNode,然后将其类型转换为Document如下所示:

Document newDocument = (Document) node.cloneNode(true);
于 2020-09-20T05:06:08.087 回答
0

也许您可以使用以下代码:

String xmlResult = XMLHelper.nodeToXMLString(node);
Document docDataItem = DOMHelper.stringToDOM(xmlResult);    
于 2016-02-03T08:13:09.327 回答