Example usage for javax.xml.xpath XPathExpression evaluate

List of usage examples for javax.xml.xpath XPathExpression evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPathExpression evaluate.

Prototype

public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:Main.java

/**
 * Returns the value of the nodes described by a xpath expression
 * /*w  ww  .  j av a2s.c  o  m*/
 * @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;
}

From source file:Main.java

/**
 * Execute an xpath query on a specific node.
 *
 * The type parameter specifies the expected type of the result of the
 * query. Typical types are:/*from w  w w. j a v a2  s . com*/
 *
 *  XPathContants.NUMBER: A java Double that corresponds to a numeric
 *  literal in the XML document
 *  XPathConstants.STRING: A java String that corresponds to a text literal
 *  in the XML document
 *  XPathConstants.NODESET: A NodeList that contains a list of nodes
 *  in the XML document
 *  XPathConstants.NODE: A particular Node inside the XML document
 *
 * @param doc The node on which the xpath expression is to be executed
 * @param xpath_expr The XPath expression to be executed
 * @param type One of the XPathConstants that specified the expected output.
 * @return The result of the XPath query on the node, of the corresponding
 *         type
 */
@SuppressWarnings("unchecked")
public static <T> T xpath(Node doc, String xpath_expr, QName type) {
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    XPathExpression expr;
    try {
        expr = xpath.compile(xpath_expr);
        return (T) expr.evaluate(doc, type);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.thoughtworks.go.util.XpathUtils.java

public static boolean nodeExists(InputSource inputSource, String xpath) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPathExpression expression = factory.newXPath().compile(xpath);
    Boolean b = (Boolean) expression.evaluate(inputSource, XPathConstants.BOOLEAN);
    return b != null && b;
}

From source file:Main.java

/**
 * Checks in under a given root element whether it can find a child elements
 * which match the XPath expression supplied. Returns a {@link List} of
 * {@link Element} if they exist./*  w  w w  .  j a va2s.co m*/
 * 
 * Please note that the XPath parser used is NOT namespace aware. So if you
 * want to find a element <beans><sec:http> you need to use the following
 * XPath expression '/beans/http'.
 * 
 * @param xPathExpression the xPathExpression
 * @param root the parent DOM element
 * 
 * @return a {@link List} of type {@link Element} if discovered, otherwise null
 */
public static List<Element> findElements(String xPathExpression, Element root) {
    List<Element> elements = new ArrayList<Element>();
    NodeList nodes = null;

    try {
        XPathExpression expr = xpath.compile(xPathExpression);
        nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException("Unable evaluate xpath expression", e);
    }

    for (int i = 0; i < nodes.getLength(); i++) {
        elements.add((Element) nodes.item(i));
    }
    return elements;
}

From source file:Main.java

public static String findInXml(String xml, String xpath) {
    try {//from w  w  w.  j  a  v a2 s  . c om
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                //                    if (systemId.contains("foo.dtd")) {
                return new InputSource(new StringReader(""));
                //                    } else {
                //                        return null;
                //                    }
            }
        });
        Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPathExpression expr = xPathfactory.newXPath().compile(xpath);
        return (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:Main.java

public static void deepCopyDocument(Document ttml, File target) throws IOException {
    try {/* ww  w. j  a v  a 2  s . co  m*/
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("//*/@backgroundImage");
        NodeList nl = (NodeList) expr.evaluate(ttml, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            Node backgroundImage = nl.item(i);
            URI backgroundImageUri = URI.create(backgroundImage.getNodeValue());
            if (!backgroundImageUri.isAbsolute()) {
                copyLarge(new URI(ttml.getDocumentURI()).resolve(backgroundImageUri).toURL().openStream(),
                        new File(target.toURI().resolve(backgroundImageUri).toURL().getFile()));
            }
        }
        copyLarge(new URI(ttml.getDocumentURI()).toURL().openStream(), target);

    } catch (XPathExpressionException e) {
        throw new IOException(e);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:Main.java

/**
 * Evaluates the XPath expression in the specified context and returns the found element as a String.
 *
 * @param node       the XML document to evaluate
 * @param expression the compiled XPath expression
 * @return the element if it was found, or null
 *//*ww w.ja  v a  2 s .c  o  m*/
public static String getStringValue(Node node, XPathExpression expression) {
    try {
        return (String) expression.evaluate(node, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        return null;
    }
}

From source file:Main.java

public static void pokeValue(final Document doc, final String xpathExpression, final String value)
        throws XPathExpressionException {
    final XPath xPath = XPF.newXPath();
    final XPathExpression expression = xPath.compile(xpathExpression);

    final Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);
    // or setValue()?
    node.setTextContent(value);/*  w  w  w. j a  va 2s  . c  om*/
}

From source file:Main.java

public static Object evalXPathExpr(String pathExpr, Document xmlDocument, QName returnType) {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpathObj = xPathFactory.newXPath();
    XPathExpression expr;
    Object result = null;//from   w  w  w  . j a  va  2  s  . c  o m
    try {
        expr = xpathObj.compile(pathExpr);
        result = expr.evaluate(xmlDocument, returnType);
    } catch (XPathExpressionException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return result;
}

From source file:Main.java

/**
 * Extract the parameters specified in the XML document for the Element
 * specified by parent.//from   w  ww  . j  a va2 s  .  com
 * 
 * @param parent
 *            - Parent Node.
 * @return
 * @throws Exception
 */
public static HashMap<String, Object> parseParams(Element parent) throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    // XPath Query for showing all nodes value
    XPathExpression expr = xpath.compile(_PARAM_NODE_PARAMS_);

    NodeList nodes = (NodeList) expr.evaluate(parent, XPathConstants.NODESET);
    if (nodes != null && nodes.getLength() > 0) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        for (int ii = 0; ii < nodes.getLength(); ii++) {
            Element elm = (Element) nodes.item(ii);
            String name = elm.getAttribute(_PARAM_ATTR_NAME_);
            String value = elm.getAttribute(_PARAM_ATTR_VALUE_);
            if (name != null && !name.isEmpty()) {
                params.put(name, value);
            }
        }
        return params;
    }
    return null;
}