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?
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.
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();
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With