Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.IOException;
import java.io.StringReader;

import java.util.ArrayList;
import java.util.List;
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 org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {
    private static XPathFactory xPathFactory = XPathFactory.newInstance();

    /**
     * Returns the value of the nodes described by a xpath expression
     * 
     * @param xml
     *            the xml string
     * @param xpathExpression
     *            the xpath expression
     * @return the text value of the nodes described by the xpath expression
     * @throws XPathExpressionException
     */

    public static List<String> getNodeValues(String xml, String xpathExpression) throws XPathExpressionException {
        List<String> nodeValues = new ArrayList<String>();
        Document doc = parseXml(xml);
        XPath xpath = xPathFactory.newXPath();
        XPathExpression expr = xpath.compile(xpathExpression);
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            nodeValues.add(nodes.item(i).getNodeValue());
        }
        return nodeValues;
    }

    /**
     * Transforms a xml String in a Document
     * 
     * @param xmlString
     *            the xml Stirng
     * @return The Document resulted from xmlString
     */
    private static Document parseXml(String xmlString) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(xmlString));
            return db.parse(is);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}