Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 1000
Svish Avatar asked Nov 08 '12 17:11

Svish


People also ask

What is org w3c DOM document?

Package org. w3c. dom Description. Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing. The Document Object Model Level 2 Core API allows programs to dynamically access and update the content and structure of documents.

How do I convert an element to a document?

Element element = //code to get a element Node node = //code to get a node //document from Node Document document = node. getOwnerDocument(); //document from a Element Document document = element. getOwnerDocument();

How do I convert a file to string in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion. String convertDocumentToString(Document doc) : This method will take input as Document and convert it to String.


1 Answers

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);
like image 191
Mark Butler Avatar answered Oct 03 '22 06:10

Mark Butler