Convert org.w3c.dom.Node into Document
Asked Answered
T

5

22

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?

Travers answered 8/11, 2012 at 17:55 Comment(1)
This is related to #3184768Surakarta
S
25

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);
Surakarta answered 14/1, 2013 at 8:39 Comment(0)
G
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.

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.

Gullett answered 8/11, 2012 at 18:10 Comment(2)
Alright, guess I just have to accept it then :p Yeah, in my actual code I have created an XmlHelper which handles the factories and such.Travers
@Svish: Right - and if you need to do this in more than one place, you could easily write a createDocument method in your helper class :)Gullett
H
1

document from Node

Document document = node.getOwnerDocument();
Hallucinosis answered 28/1, 2020 at 8:19 Comment(1)
Just wish to point out that, using node.getOwnerDocument() return the entire original document, not the sub portion that that node can represent.Rania
E
1

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

Document newDocument = (Document) node.cloneNode(true);
Explode answered 20/9, 2020 at 5:6 Comment(0)
L
0

Maybe you can use this code:

String xmlResult = XMLHelper.nodeToXMLString(node);
Document docDataItem = DOMHelper.stringToDOM(xmlResult);    
Lasala answered 3/2, 2016 at 8:13 Comment(1)
The answer should at least point where to find XMLHelper's and DOMHelper's implementations as they're not in the Java standard library.Reface

© 2022 - 2024 — McMap. All rights reserved.