Java XML Parse File parseXml(String filePath)

Here you can find the source of parseXml(String filePath)

Description

Creates W3C DOM Document object from XML file

License

Open Source License

Parameter

Parameter Description
filePath path to xml file including file name and extension

Declaration

public static Document parseXml(String filePath) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.xml.sax.SAXException;

public class Main {
    /**/* w  ww  . j av  a  2 s .  c  o m*/
     * Creates W3C DOM Document object from XML file
     * @param filePath path to xml file including file name and extension
     */
    public static Document parseXml(String filePath) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(filePath);
            doc.getDocumentElement().normalize();
            return doc;
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
            return null;
        } catch (SAXException se) {
            se.printStackTrace();
            return null;
        } catch (IOException ioe) {
            //ioe.printStackTrace();
            String toRemove = File.separator + "WebApp" + File.separator;
            Document doc;
            try {
                DocumentBuilder db = dbf.newDocumentBuilder();
                doc = db.parse(filePath.replace(toRemove, File.separator));
                doc.getDocumentElement().normalize();
                return doc;
            } catch (SAXException saxex) {
                saxex.printStackTrace();
                return null;
            } catch (ParserConfigurationException pcex) {
                pcex.printStackTrace();
                return null;
            } catch (IOException ioex) {
                ioex.printStackTrace();
                return null;
            }
        }
    }
}

Related

  1. parseXml(File file)
  2. parseXml(File file)
  3. parseXML(final File file)
  4. parseXml(String fileName)
  5. parseXml(String filename, boolean validating)
  6. parseXml(String filePath)
  7. parseXml(String value, boolean isFile)
  8. parseXMLFile(File f)
  9. parseXmlFile(File file)