Convert org.w3c.dom.Node into Document

谁都会走 提交于 2019-12-06 17:30:42

问题


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?


回答1:


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:


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.




回答3:


Maybe you can use this code:

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


来源:https://stackoverflow.com/questions/13294884/convert-org-w3c-dom-node-into-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!