Recuperar un Node con XPath

2018 vistas

Veamos un método que permite recuperar un Node (package org.w3c.dom) con XPath.



java
  1. public static Node evaluador(InputStream stream, String expression){
  2.   Node nodo = null;
  3.   try{
  4.       // creación del source
  5.       InputSource source = new InputSource(stream);
  6.  
  7.       // creación del XPath
  8.       XPathFactory factory = XPathFactory.newInstance();
  9.       XPath xpath = factory.newXPath();
  10.  
  11.       // evaluar la expresión XPath
  12.       XPathExpression exp = xpath.compile(expression);
  13.       nodo = (Node)exp.evaluate(source,XPathConstants.NODE);
  14.   }catch(XPathExpressionException xpee){
  15.       xpee.printStackTrace();
  16.   }
  17.   return nodo;
  18. }