Create XML Document object from a File - Java XML

Java examples for XML:DOM Document

Description

Create XML Document object from a File

Demo Code


//package com.java2s;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class Main {
    /**//from  w  w  w. j ava 2s  .co m
     * Create a Document object from a File
     * 
     * @param pathToDocument
     *          The path to a File that should be loaded
     *          into a Document
     * 
     * @return
     *          The Document that was created from the path.
     *          A RuntimeException gets thrown if a Document
     *          fails to be created.
     */
    public static Document createDocument(String pathToDocument) {

        try {
            DocumentBuilderFactory dbfac = DocumentBuilderFactory
                    .newInstance();

            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

            return docBuilder.parse(pathToDocument);

        } catch (Exception e) {
            throw new RuntimeException(
                    "Unabled to create document from file: "
                            + pathToDocument, e);
        }
    }
}

Related Tutorials