Java XPath Get getNodeByXPath(Object context, String expression)

Here you can find the source of getNodeByXPath(Object context, String expression)

Description

Evaluates an XPath expression and returns a single matching node.

License

Apache License

Parameter

Parameter Description
context The context in which to run the expression.
expression A valid XPath expression.

Exception

Parameter Description
XPathException If the provided expression is invalid or multiple nodes match.

Return

, if one is found, null otherwise.

Declaration

public static Node getNodeByXPath(Object context, String expression) throws XPathException 

Method Source Code

//package com.java2s;
/**/*  w  w w .  j  ava  2  s. co  m*/
 * Copyright 2015 Nortal Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and limitations under the
 * License.
 **/

import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;

public class Main {
    /**
     * Evaluates an {@link XPath} expression and returns a <i>single</i> matching node.
     *
     * @param context The context in which to run the expression.
     * @param expression A valid {@link XPath} expression.
     * @return {@link Node}, if one is found, <code>null</code> otherwise.
     * @throws XPathException If the provided expression is invalid or multiple nodes match.
     */
    public static Node getNodeByXPath(Object context, String expression) throws XPathException {
        return (Node) XPathFactory.newInstance().newXPath().evaluate(expression, context, XPathConstants.NODE);
    }
}

Related

  1. getNewXPath()
  2. getNewXPath()
  3. getNode(Node node, XPathExpression xpath)
  4. getNode(String xPathExpression, Node node)
  5. getNodeByXPath(Document document, String xPath)
  6. getNodeList(Element root, String xpath)
  7. getNodeList(File xml, String xpathExpression)
  8. getNodeList(final String expr, final File xmlFile)
  9. getNodeList(InputStream stream, String pattern)