克隆dom.Document对象 [英] Cloning dom.Document object
本文介绍了克隆dom.Document对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目的是将xml文件读入Dom对象,编辑dom对象,这涉及删除一些节点。
My purpose is to read xml file into Dom object, edit the dom object, which involves removing some nodes.
完成之后,我希望将Dom恢复到原始状态,而无需实际解析XML文件。
After this is done i wish to restore the Dom to its original state without actually parsing the XML file.
无论如何,我可以克隆第一次解析xml文件后获得的dom对象。这个想法是避免一直读取和解析xml,只需保留原始的dom树的副本。
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.
推荐答案
你可以使用 importNode org.w3c.dom.Document上的API:
You could use importNode API on org.w3c.dom.Document:
Node copy = document.importNode(node, true);
完整示例
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);
}
}
这篇关于克隆dom.Document对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文