18

My purpose is to read xml file into Dom object, edit the dom object, which involves removing some nodes.

After this is done i wish to restore the Dom to its original state without actually parsing the XML file.

Is there anyway i can clone the dom object i obtained after parsing the xml file for the first time. the idea is to avoid reading and parsing xml all the time, just keep a copy of original dom tree.

1

4 Answers 4

19

You could use importNode API on org.w3c.dom.Document:

Node copy = document.importNode(node, true);

Full Example

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document originalDocument = db.parse(new File("input.xml"));
        Node originalRoot = originalDocument.getDocumentElement();

        Document copiedDocument = db.newDocument();
        Node copiedRoot = copiedDocument.importNode(originalRoot, true);
        copiedDocument.appendChild(copiedRoot);

    }
}
2
  • Beware, this way of copying the document will remove processing instructions or comments within the file! Commented Jan 15, 2014 at 16:46
  • I believe this will remove any UserData that was appended to any nodes in the old document! It makes sense that it does that, but one has to be aware
    – ParkerHalo
    Commented Aug 9, 2016 at 10:14
9
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer tx   = tfactory.newTransformer();
DOMSource source = new DOMSource(doc);
DOMResult result = new DOMResult();
tx.transform(source,result);
return (Document)result.getNode();

This would be the Java 1.5 solution for making a copy of the DOM document. Take a look at Transformer Factory and Transformer

2
  • isEqualNode() doesn't return true if you copy in this way
    – ka3ak
    Commented Feb 26, 2012 at 8:55
  • 2
    This method keeps processing instructions and comments in the copy! Commented Jan 15, 2014 at 16:47
9

you could clone a tree or only the node with DOMs cloneNode(boolean isDeepCopy) API.

Document originalDoc = parseDoc();
Document clonedDoc = originalDoc.cloneNode(true);

unfortunately, since cloneNode() on Document is (according to API) implementation specific, we have to go for a bullet-proof way, that is, create a new Document and import cloned node's from the original document:

...
Document clonedDoc = documentFactory.newDocument();
cloneDoc.appendChild(
  cloneDoc.importNode(originalDoc.getDocumentElement(), true)
);

note that none of operations are thread-safe, so either use them only locally, or Thread-Local or synchronize them.

1

I would stick with the second suggestion with TransformerFactory. With importNode you don't get a full copy of the document. The header isn't copied.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?aid style="50" type="snippet" readerVersion="6.0" featureSet="257" product="8.0(370)" ?>      
<?aid SnippetType="PageItem"?><Document DOMVersion="8.0" Self="d">

This would not return the above because this isn't copied. It's will be using what ever your new document contain.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.