Java Utililty Methods XPath Expression

List of utility methods to do XPath Expression

Description

The list of methods to do XPath Expression are organized into topic(s).

Method

StreamstreamNodes(String xpath, Object node)
stream Nodes
return stream((NodeList) evaluateXPath(xpath, node, XPathConstants.NODESET));
Stringstring(Node context, String expression)
string
try {
    String result = (String) xpath.evaluate(expression, context, XPathConstants.STRING);
    if (result == null || result.length() == 0)
        return null;
    else
        return result;
} catch (XPathExpressionException ex) {
    ex.printStackTrace();
...
Stringstring(String fileName, String xpathExpression)
string
TransformerFactory transFact = TransformerFactory.newInstance();
try {
    Transformer transFormer = transFact.newTransformer();
    DOMResult dom = new DOMResult();
    transFormer.transform(new StreamSource(new FileInputStream(new File(fileName))), dom);
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expression = xpath.compile(xpathExpression);
    String value = (String) expression.evaluate(dom.getNode(), XPathConstants.STRING);
...
StringvalueOf(Node node, String xpath, NamespaceContext context)
Evaluates an XPath expression given a namespace context and returns the String value of the result, similar to the value-of function in XSLT.
try {
    xpathObj.setNamespaceContext(context);
    String result = (String) xpathObj.evaluate(xpath, node, XPathConstants.STRING);
    xpathObj.reset();
    return result;
} catch (XPathExpressionException e) {
    return "";
StringxmlValueOf(Node node, String xpathExpression)
Returns the textual representation after evaluating the xpathExpression.
List nodes = xmlSelectNodes(node, xpathExpression);
StringBuffer buf = new StringBuffer();
for (Iterator i = nodes.iterator(); i.hasNext();) {
    Node n = (Node) i.next();
    String str = xmlGetText(n);
    if (str != null)
        buf.append(str);
return buf.toString();
StringxPathStr(String expr, Object context)
x Path Str
try {
    return xPath().evaluate(expr, context);
} catch (XPathExpressionException e) {
    throw new IllegalArgumentException(expr, e);
NodexpathToNode(String xpathQuery, Object domObject)
xpath To Node
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
return (Node) xpath.evaluate(xpathQuery, domObject, XPathConstants.NODE);
StringXPathValueFromString(String sIn, String sxpath)
Returns the xml value.
Document doc = loadXMLFromString(sIn);
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile(sxpath);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
String sReturn = "";
for (int i = 0; i < nodes.getLength(); i++) {
    sReturn = nodes.item(i).getNodeValue();
...