Creates a DOM from a file representation of an xml record - Java XML

Java examples for XML:DOM

Description

Creates a DOM from a file representation of an xml record

Demo Code


import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main{
    /** Creates a DOM from a file representation of an xml record
     * @param doc the xml file//from w  ww.jav  a  2s . c  o  m
     * @return the DOM document
     */
    public static Document parseDomFromFile(File doc)
            throws org.xml.sax.SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        try {
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(new org.xml.sax.InputSource(
                    new FileReader(doc)));
        } catch (javax.xml.parsers.ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
    }
    /** Creates a DOM from a file representation of an xml record
     * @param doc the xml file
     * @return the DOM document
     */
    public static Document parseDomFromFile(File doc, String encoding)
            throws org.xml.sax.SAXException {
        return parseDomFromFile(doc, encoding, false);
    }
    /** Creates a DOM from a file representation of an xml record
     * @param doc the xml file
     * @return the DOM document
     */
    public static Document parseDomFromFile(File doc, String encoding,
            boolean namespaceAware) throws org.xml.sax.SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        factory.setNamespaceAware(namespaceAware);
        try {
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(new org.xml.sax.InputSource(
                    new StringReader(FileUtil.readFileToString(doc,
                            encoding))));
        } catch (javax.xml.parsers.ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials