App下載
首頁(yè)javadomJava HTML/XML - 如何克隆dom.Document對(duì)象

Java HTML/XML - 如何克隆dom.Document對(duì)象

我們想知道如何克隆dom.Document對(duì)象。
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 Main {

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

  }
}