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;

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

    public static Object execXpathGetNodeList(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.NODESET);
        } 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;
    }
}