/**
 * 
 */
package cz.neubauer.tomas.hazardanalysis.model;

import java.io.IOException;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * @author Tomáš Neubauer
 */
public class XMLReader {

	/**
	 * Provede na daném XML souboru příkaz XPath a vrátí jeho výsledek.
	 * 
	 * @param path
	 *            Cesta k souboru XML.
	 * @param xPath
	 *            Program jazyka XPath.
	 * @param returnType
	 *            Typ návratové hodnoty.
	 * @return
	 */
	public static Object readXML(String path, String xPath, QName returnType) {
		if (path == null) {
			return null;
		}
		Object retval = null;

		try {
			DocumentBuilderFactory domFactory = DocumentBuilderFactory
					.newInstance();
			domFactory.setNamespaceAware(false);
			DocumentBuilder builder;

			builder = domFactory.newDocumentBuilder();

			Document doc = builder.parse(path);

			XPathFactory factory = XPathFactory.newInstance();
			XPath xpath = factory.newXPath();

			XPathExpression expr = xpath.compile(xPath);
			retval = expr.evaluate(doc, returnType);

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return retval;
	}
}
