Convert org.w3c.dom.Node into Document

半世苍凉 提交于 2019-12-05 00:46:22
Mark Butler

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

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.

Julie Ann C. Ramos

Maybe you can use this code:

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