Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning dom.Document object

Tags:

java

dom

xml

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.

like image 539
Kazoom Avatar asked Mar 08 '11 00:03

Kazoom


People also ask

What is a clone node?

Definition and Usage. The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).

How do I clone a div using JavaScript?

to add the div. Then we can clone the div by writing: const div = document. getElementById('foo') const clone = div.

What is cloneNode in JavaScript?

The cloneNode() method in JavaScript makes a duplicate of the node object that is sent in and delivers the clone node object. On the element you would like to copy, simply call the cloneNode() method. Pass true as an option if you wish to copy the element's nested elements as well.


1 Answers

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);

    }
}
like image 123
bdoughan Avatar answered Sep 22 '22 09:09

bdoughan