Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

public class Main {
    private static final XPathFactory XPF = XPathFactory.newInstance();
    private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();

    public static String peekValue(final Document doc, final String xpathExpression)
            throws XPathExpressionException {
        final XPath xPath = XPF.newXPath();
        final XPathExpression expression = xPath.compile(xpathExpression);

        final Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);
        final String result = (node != null) ? node.getTextContent() : null;
        return result;
    }

    public static String peekValue(final File file, final String xpathExpression)
            throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
        final DocumentBuilder db = DBF.newDocumentBuilder();
        final FileInputStream fis = new FileInputStream(file);
        final Document doc;
        try {
            doc = db.parse(fis);
        } finally {
            fis.close();
        }

        final String result = peekValue(doc, xpathExpression);
        return result;
    }
}