Java XML Element Root getRootElement(String location)

Here you can find the source of getRootElement(String location)

Description

return the root Element of an XML file with given location

License

Open Source License

Parameter

Parameter Description
location a parameter

Return

Element the root element, or null if there is any problem

Declaration

public static Element getRootElement(String location) throws Exception 

Method Source Code


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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;

import org.xml.sax.SAXException;

public class Main {
    /**/*from  ww w  .jav  a2 s  .  c om*/
     * return the root Element of an XML file with given location
     * @param location
     * @return Element the root element, or null if there is any problem
     */
    public static Element getRootElement(String location) throws Exception {
        Element root = null;
        try {
            FileInputStream fi = new FileInputStream(location);
            DocumentBuilderFactory builderFac = DocumentBuilderFactory.newInstance();
            builderFac.setNamespaceAware(true);
            root = builderFac.newDocumentBuilder().parse(fi).getDocumentElement();
        } catch (SAXException ex) {
            notify(location, ex);
        } catch (FileNotFoundException ex) {
            notify(location, ex);
        } catch (IOException ex) {
            notify(location, ex);
        } catch (ParserConfigurationException ex) {
            notify(location, ex);
        }
        return root;
    }

    private static void notify(String location, Exception ex) throws Exception {
        throw new Exception("Exception getting XML root element from " + location + "; " + ex.getMessage());
    }
}

Related

  1. getRootElement(final Element descendant)
  2. getRootElement(final File definition)
  3. getRootElement(final String respuestaPost)
  4. getRootElement(final XMLEventReader bufferedXmlEventReader)
  5. getRootElement(String elementName, String namespace, String prefix)
  6. getRootElementFromString(String payload)
  7. getRootElementName(Class clazz)
  8. getRootElementPosition(String buf, Element root)
  9. getRootFaceletElement(Document document)