Svish
Svish

Reputation: 157971

Convert org.w3c.dom.Node into 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?

Upvotes: 22

Views: 31886

Answers (5)

Ashutosh Pandey
Ashutosh Pandey

Reputation: 11

You can simply clone the old document using cloneNode and then typecast it to Document like below:

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

Upvotes: 1

Armer B.
Armer B.

Reputation: 772

document from Node

Document document = node.getOwnerDocument();

Upvotes: 1

Julie Ann C. Ramos
Julie Ann C. Ramos

Reputation: 9

Maybe you can use this code:

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

Upvotes: 0

Mark Butler
Mark Butler

Reputation: 4391

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

Upvotes: 25

Jon Skeet
Jon Skeet

Reputation: 1499760

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.

Upvotes: 6

Related Questions