Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.util.ArrayList;

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;
import org.w3c.dom.NodeList;

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

    public static ArrayList<Node> getNodesXPath(String srcXmlString, String xPath) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false); // never forget this!
        Document doc = null;
        DocumentBuilder builder = null;
        ArrayList<Node> nodesList = new ArrayList<Node>();
        try {
            builder = domFactory.newDocumentBuilder();
            doc = builder.parse(new ByteArrayInputStream(srcXmlString.getBytes()));
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(xPath);

            Object result = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList xPathNodes = (NodeList) result;
            logger.debug("xpath result count: " + xPathNodes.getLength());
            // iterate through all the nodes
            for (int i = 0; i < xPathNodes.getLength(); i++) {
                nodesList.add(xPathNodes.item(i));
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        return nodesList;
    }
}