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?
这是可行的,但我觉得有点烦人。是否有一种更少的冗长/更直接的方式我看不到,或者我必须这样做?
3 个解决方案
#1
10
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);
#2
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.
我觉得差不多。虽然它看起来确实很冗长,但它显然不会比使用DOM API的其他代码看起来更冗长。不幸的是,这只是一个烦人的API。
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.
当然,如果您已经有了一个来自其他地方的DocumentBuilder,那么它会更简单——这将删除大量的代码。
#3
0
Maybe you can use this code:
也许你可以使用这个代码:
String xmlResult = XMLHelper.nodeToXMLString(node);
Document docDataItem = DOMHelper.stringToDOM(xmlResult);
#1
10
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);
#2
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.
我觉得差不多。虽然它看起来确实很冗长,但它显然不会比使用DOM API的其他代码看起来更冗长。不幸的是,这只是一个烦人的API。
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.
当然,如果您已经有了一个来自其他地方的DocumentBuilder,那么它会更简单——这将删除大量的代码。
#3
0
Maybe you can use this code:
也许你可以使用这个代码:
String xmlResult = XMLHelper.nodeToXMLString(node);
Document docDataItem = DOMHelper.stringToDOM(xmlResult);