Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class Main {
    private static Logger logger = Logger.getLogger(new Exception().getStackTrace()[0].getClassName());

    public static String getValueXPath(String srcXmlString, String xPath) {
        String value = null;
        try {
            Object result = execXpathGetNode(srcXmlString, xPath);
            Node node = (Node) result;
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                value = node.getTextContent();
            } else {
                value = node.getNodeValue();
            }
            logger.debug(xPath + " = " + value);
        } catch (Exception ex) {
            logger.error(ex.getMessage() + " Could not extract any value using xpath: " + xPath);
        }
        return value;
    }

    public static Object execXpathGetNode(String srcXmlString, String xPath) {
        Object result = null;
        try {
            Document doc = stringToDoc(srcXmlString);
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(xPath);
            result = expr.evaluate(doc, XPathConstants.NODE);
        } catch (Exception ex) {
            logger.error(ex);
        }
        return result;
    }

    public static Document stringToDoc(String srcXmlString) {
        Document doc = null;
        try {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(false); // never forget this!
            DocumentBuilder builder = null;
            builder = domFactory.newDocumentBuilder();
            doc = builder.parse(new ByteArrayInputStream(srcXmlString.getBytes()));
        } catch (Exception ex) {
            logger.error(ex);
        }
        return doc;
    }
}