Search code examples
javaxmldomxml-namespacesxmldom

How to construct a new document builder out of an existing builders node?


I have the following code:

DocumentBuilderFactory dbFactory_ = DocumentBuilderFactory.newInstance();
Document doc_;
DocumentBuilder dBuilder = dbFactory_.newDocumentBuilder();
StringReader reader = new StringReader(s);
InputSource inputSource = new InputSource(reader);
doc_ = dBuilder.parse(inputSource);
doc_.getDocumentElement().normalize();

and then I traverse doc_ in order to get a specific node. I would then like to create a new dBuilder with that node. What I've been trying so far with little success is to convert my node to a string and then have the dBuilder.parse the string but that has not been working because I'm running into namespace problems and other things.

<Random>
  <Fixed></Fixed>
</Random>

So with this I would take the <Fixed> node out and create a completely new class where it is the root node.


Solution

  • Create a new document and then import your node into it, as shown below:

    Document otherDoc = dBuilder.newDocument();
    Node importedNode = otherDoc.importNode(myNode, true);
    otherDoc.appendChild(importedNode);