Creates a XML document from the specified file. - Android XML

Android examples for XML:XML Document

Description

Creates a XML document from the specified file.

Demo Code


//package com.java2s;
import java.io.File;

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

public class Main {
    public static void main(String[] argv) {
        File documentFile = new File("Main.java");
        System.out.println(documentFrom(documentFile));
    }/*from  w ww  .j a v  a 2s  .  com*/

    /**
     * Creates a document from the specified file.
     */
    public static Document documentFrom(File documentFile) {
        if (!documentFile.exists()) {
            throw new IllegalStateException(documentFile.getAbsolutePath()
                    + " file not found.");
        }
        final DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        try {
            final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc;
            doc = dBuilder.parse(documentFile);
            doc.getDocumentElement().normalize();
            return doc;
        } catch (final Exception e) {
            throw new RuntimeException("Error while parsing file "
                    + documentFile.getPath(), e);
        }
    }
}

Related Tutorials