将org.w3c.dom.Node转换为Document [英] Convert org.w3c.dom.Node into Document

查看:1455
本文介绍了将org.w3c.dom.Node转换为Document的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个文档获得节点。我想把节点并将其转换为新的文档的根节点。

I have a Node from one Document. I want to take that Node and turn it into the root node of a new Document.

我能想到的唯一方法如下:

Only way I can think of is the following:

Node node = someChildNodeFromDifferentDocument;

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

DocumentBuilder builder = factory.newDocumentBuilder();

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

这样可行,但我觉得这很烦人。有没有更简洁/更直接的方式我没有看到,或者我只是必须这样做?

This works, but I feel it is rather annoyingly verbose. Is there a less verbose/more direct way I'm not seeing, or do I just have to do it this way?

推荐答案

代码对我不起作用 - 但是有一些变化相关问题我可以按照以下方式使用它:

The code did not work for me - but with some changes from this related question I could get it to work as follows:

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

这篇关于将org.w3c.dom.Node转换为Document的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆