Java XPath Get xGetNode(Node targetNode, String expression)

Here you can find the source of xGetNode(Node targetNode, String expression)

Description

Uses the passed XPath expression to locate a single node in the passed element.

License

LGPL

Parameter

Parameter Description
targetNode The node to search.
expression The XPath expression.

Return

The located node or null if one is not found.

Declaration

public static Node xGetNode(Node targetNode, String expression) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import org.w3c.dom.*;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import static javax.xml.xpath.XPathConstants.NODE;

public class Main {
    /**//from  w  ww. j ava2  s. c o m
     * Uses the passed XPath expression to locate a single node in the passed element.
     * @param targetNode The node to search.
     * @param expression The XPath expression.
     * @return The located node or null if one is not found.
     */
    public static Node xGetNode(Node targetNode, String expression) {
        Node node = null;
        XPath xpath = null;
        try {
            xpath = XPathFactory.newInstance().newXPath();
            XPathExpression xpathExpression = xpath.compile(expression);
            node = (Node) xpathExpression.evaluate(targetNode, NODE);
            return node;
        } catch (Exception e) {
            throw new RuntimeException("XPath:Failed to locate the node:" + expression, e);
        }
    }
}

Related

  1. getValueByPath(Node node, String path)
  2. getValueByXpath(Node doc, String xquery)
  3. getValueFromXML(final String inputXML, final String xPathQuery, final int index)
  4. getValues(final String expression, final String xml)
  5. getX_PATH()