XPath evaluate expression and return element - Java XML

Java examples for XML:XPath

Description

XPath evaluate expression and return element

Demo Code


//package com.java2s;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
    static private XPath xpath;

    static public Element element(Node context, String expression) {
        try {/*w ww .j  a v  a2  s.  c om*/
            return (Element) xpath.evaluate(expression, context,
                    XPathConstants.NODE);
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            throw new RuntimeException("invalid xpath expresion used");
        }
    }
}

Related Tutorials