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.io.IOException;

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

import javax.xml.xpath.*;

import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

public class Main {
    public static NodeList getNodes(final Object doc, final String query) throws XPathExpressionException {
        final XPath xpath = XPathFactory.newInstance().newXPath();
        final XPathExpression expr = xpath.compile(query);
        return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    }

    public static NodeList getNodes(final Document doc, final String query) throws XPathExpressionException {
        final XPath xpath = XPathFactory.newInstance().newXPath();
        final XPathExpression expr = xpath.compile(query);
        return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    }

    public static NodeList getNodes(final String xml, final String query)
            throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
        return getNodes(getDocument(xml), query);
    }

    public static Document getDocument(final String xml)
            throws ParserConfigurationException, SAXException, IOException {
        final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        final DocumentBuilder builder = domFactory.newDocumentBuilder();
        return builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
    }
}