将org.w3c.dom.Node转换为Document。

20

我有来自一个DocumentNode。我想将该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);

这个方法是有效的,但我觉得写起来太啰嗦了。有没有更简洁/直接的方法?还是说只能用这种方式?


这与https://dev59.com/X-o6XIcBkEYKwwoYTy8d有关。 - Mark Butler
5个回答

24

这段代码在我这里无法运行,但通过参考这个相关问题并进行一些修改,最终成功运行:

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);

6

在我看来,这差不多就是了。虽然看起来有点啰嗦,但相比使用DOM API的其他代码,并没有显著增加太多冗余。不幸的是,它只是一个令人讨厌的API。

当然,如果你已经从其他地方获得了一个DocumentBuilder,那么这将简单得多 - 这样可以省去很多代码。


好的,我猜我只能接受它了 :p 是的,在我的实际代码中,我创建了一个XmlHelper来处理工厂等内容。 - Svish
@Svish:没错 - 如果你需要在多个地方执行这个操作,你可以很容易地在你的帮助类中编写一个createDocument方法 :) - Jon Skeet

1

来自Node的文档

Document document = node.getOwnerDocument();

5
只是想指出,使用 node.getOwnerDocument() 返回的是整个原始文档,而不是 node 可能代表的子部分。 - Zaxxon

0

也许你可以使用这段代码:

String xmlResult = XMLHelper.nodeToXMLString(node);
Document docDataItem = DOMHelper.stringToDOM(xmlResult);    

9
答案至少应指出XMLHelper和DOMHelper的实现在哪里可以找到,因为它们不在Java标准库中。 - igorcadelima

0

您可以使用cloneNode克隆旧文档,然后像下面这样将其强制转换为Document

Document newDocument = (Document) node.cloneNode(true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接