Search code examples
javaxmlxmlbeans

How to insert XmlCursor content to DOM Document


Some API returns me XmlCursor pointing on root of XML Document. I need to insert all of this into another org.w3c.DOM represented document.

At start: XmlCursor poiting on

<a> <b> some text </b> </a>

DOM Document:

<foo>

</foo>

At the end I want to have original DOM document changed like this:

<foo>

  <someOtherInsertedElement>

    <a> <b> some text </b> </a>

  </someOtherInsertedElement>

</foo>

NOTE: document.importNode(cursor.getDomNode()) doesn't work - Exception is thrown: NOT_SUPPORTED_ERR: The implementation does not support the requested type of object or operation.


Solution

  • Try something like this:

    Node originalNode = cursor.getDomNode();
    Node importNode = document.importNode(originalNode.getFirstChild());
    Node otherNode = document.createElement("someOtherInsertedElement");
    otherNode.appendChild(importNode);
    document.appendChild(otherNode);
    

    So in other words:

    1. Get the DOM Node from the cursor. In this case, it's a DOMDocument, so do getFirstChild() to get the root node.
    2. Import it into the DOMDocument.
    3. Do other stuff with the DOMDocument.
    4. Append the imported node to the right Node.

    The reason to import is that a node always "belongs" to a given DOMDocument. Just adding the original node would cause exceptions.