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

public static List<Node> evaluateNodeListXPath(final Document document, final XPathExpression expression)
        throws XPathExpressionException {
    notNull(document);//from   www  . ja  v a 2  s  . c o m
    notNull(expression);

    final List<Node> result = new LinkedList<Node>();

    final NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);

    for (int node = 0; node < nodeList.getLength(); node++) {
        result.add(nodeList.item(node));
    }

    return result;
}

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. 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'.
 * /*from ww w  .  java 2s .c om*/
 * @param xPathExpression the xPathExpression
 * @param root the parent DOM element
 * @return a {@link List} of type {@link Element} if discovered, otherwise
 *         an empty list (never null)
 */
public static List<Element> findElements(final String xPathExpression, final Element root) {
    final List<Element> elements = new ArrayList<Element>();
    NodeList nodes = null;

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

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

From source file:com.amalto.core.storage.datasource.DataSourceFactory.java

private static Object evaluate(Node node, String expression, QName returnType) throws XPathExpressionException {
    XPathExpression result;
    synchronized (xPath) {
        result = xPath.compile(expression);
    }/* w w  w .  jav  a 2s  .  c o m*/
    return result.evaluate(node, returnType);
}

From source file:org.ensembl.gti.seqstore.database.cramstore.EnaCramSubmitter.java

protected static String getElemAttrib(Document doc, String tag, String attr) {
    try {/*from   w  w w.  j  ava  2  s .co  m*/
        XPathExpression acc = xpath.compile("//" + tag + "[@" + attr + "]");
        Node nl = (Node) acc.evaluate(doc, XPathConstants.NODE);
        if (nl == null) {
            return null;
        }
        Node attrN = nl.getAttributes().getNamedItem(attr);
        if (attrN == null) {
            return null;
        } else {
            return attrN.getTextContent();
        }
    } catch (XPathExpressionException e) {
        throw new EnaSubmissionException("Could not parse submission receipt", e);
    }
}

From source file:Main.java

/**
 * Counts the elements which results from the xpath expression.
 * /*from  w  ww . jav a2 s . co  m*/
 * @param document the xml document.
 * @param xpath the expression
 * @param message The assert message.
 * @return Returns -1 if no element was found.
 */
public static int count(String message, Document document, String xpath) throws XPathExpressionException {
    XPathExpression expression = EXPRESSIONS.get(xpath);
    NodeList list = null;

    if (expression == null) {
        expression = XPathFactory.newInstance().newXPath().compile(xpath);
        EXPRESSIONS.put(xpath, expression);
    }

    if ((list = (NodeList) expression.evaluate(document.getDocumentElement(),
            XPathConstants.NODESET)) != null) {
        return list.getLength();
    }

    return -1;
}

From source file:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java

public static Document replaceTokens(Document doc, Policy configTokens)
        throws XPathExpressionException, TransformerConfigurationException {

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(configTokens);
    logger.info("============= to apply the following config tokens ================\n{}", json);

    try {/*  w  w  w  .  ja  v a2s .com*/
        for (int i = 0; i < configTokens.tokens.size(); i++) {

            logger.debug("=============Checking for Xpath Expressions {}  ================\n",
                    configTokens.tokens.get(i).xpath);
            XPathExpression expression = xpath.compile(configTokens.tokens.get(i).xpath);

            NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);

            for (int j = 0; j < nodes.getLength(); j++) {

                if (nodes.item(j).hasChildNodes()) {
                    logger.debug("=============Updated existing value {} to new value {} ================\n",
                            nodes.item(j).getTextContent(), configTokens.tokens.get(i).value);
                    nodes.item(j).setTextContent(configTokens.tokens.get(i).value);
                }
            }

        }

        return doc;
    } catch (XPathExpressionException e) {

        logger.error(String.format(
                "\n\n=============The Xpath Expressions in config.json are incorrect. Please check. ================\n\n%s",
                e.getMessage()), e);
        throw e;
    }

}

From source file:Main.java

public static boolean updateDBConfig(String userName, String password, String name, String driver, String url,
        String dbConfigPath) throws XPathExpressionException, ParserConfigurationException, SAXException,
        IOException, TransformerException {
    Document document = loadXML(dbConfigPath);

    XPath path = XPathFactory.newInstance().newXPath();
    XPathExpression express = path.compile(
            "//Configure/New[@class='org.eclipse.jetty.plus.jndi.Resource']/Arg/New[@class='bitronix.tm.resource.jdbc.PoolingDataSource']/Set[@name='className']");

    NodeList nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);
    Node node = nodes.item(0);//ww  w. j av a 2 s.c om
    node.setTextContent(driver);
    path.reset();

    express = path.compile(
            "//Configure/New[@class='org.eclipse.jetty.plus.jndi.Resource']/Arg/New[@class='bitronix.tm.resource.jdbc.PoolingDataSource']/Get['@name=driverProperties']/Put");
    nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        node = nodes.item(i);
        if ("user".equals(node.getAttributes().item(0).getTextContent())) {
            node.setTextContent(userName);
        } else if ("password".equals(node.getAttributes().item(0).getTextContent())) {
            node.setTextContent(password);
        } else if ("URL".equals(node.getAttributes().item(0).getTextContent())) {
            //            String url = node.getTextContent();
            //            System.out.println("basic url ---> " + url + "; name -->" + name);
            //            url = replaceDBName("examples", name, url);
            //            System.out.println("dist url ---> " + url);
            node.setTextContent(url);
        }
    }
    path.reset();

    return updateXML(document, dbConfigPath);
}

From source file:org.alfresco.web.config.XmlUtils.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.//from   w w w. jav  a 2  s. c o 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

/**
 * Checks in under a given root element whether it can find a child element
 * which matches the XPath expression supplied. Returns {@link Element} if
 * exists./*from  www .j  ava2  s  . c  om*/
 * 
 * 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 (required)
 * @param root the parent DOM element (required)
 * 
 * @return the Element if discovered (null if not found)
 */
public static Element findFirstElement(String xPathExpression, Element root) {
    if (xPathExpression == null || root == null || xPathExpression.length() == 0) {
        throw new IllegalArgumentException("Xpath expression and root element required");
    }

    Element rootElement = null;
    try {

        XPathExpression expr = compiledExpressionCache.get(xPathExpression);
        if (expr == null) {
            expr = xpath.compile(xPathExpression);
            compiledExpressionCache.put(xPathExpression, expr);
        }
        rootElement = (Element) expr.evaluate(root, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException("Unable evaluate xpath expression", e);
    }
    return rootElement;
}

From source file:Main.java

/**
 * Checks in under a given root element whether it can find a child node
 * which matches the XPath expression supplied. Returns {@link Node} if
 * exists./*w  w w .  ja v a2 s  .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 (required)
 * @param root the parent DOM element (required)
 * 
 * @return the Node if discovered (null if not found)
 */
public static Node findNode(String xPathExpression, Element root) {
    if (xPathExpression == null || root == null || xPathExpression.length() == 0) {
        throw new IllegalArgumentException("Xpath expression and root element required");
    }
    Node node = null;
    try {
        XPathExpression expr = compiledExpressionCache.get(xPathExpression);
        if (expr == null) {
            expr = xpath.compile(xPathExpression);
            compiledExpressionCache.put(xPathExpression, expr);
        }
        node = (Node) expr.evaluate(root, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException("Unable evaluate xpath expression", e);
    }
    return node;
}