Convert a document node into a new Document which root node is the original node. - Java XML

Java examples for XML:XML Node

Description

Convert a document node into a new Document which root node is the original node.

Demo Code


//package com.java2s;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class Main {
    /**//from w  ww.  j av a 2 s . c o m
     * Convert a document node into a new Document which root node is the original node.
     * @param n The node to be converted into full document.
     * @return An instance of Document, which root is the node passed in parameter.
     */
    public static Document asDocument(Node n) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        Document newDoc = null;
        try {

            db = dbf.newDocumentBuilder();
            newDoc = db.newDocument();
            newDoc.appendChild(newDoc.importNode(n, true));

        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return newDoc;
    }
}

Related Tutorials