Java HTML / XML How to - Get a variable in xpath








Question

We would like to know how to get a variable in xpath.

Answer

import java.io.StringReader;
/*  ww  w . ja  va2 s .c  o  m*/
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

public class Main {

  public static void main(String[] args) {

    String simpleXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><person><name>Bob</name></person>";
    InputSource inputSource = new InputSource(new StringReader(simpleXML));
    XPath xpath = XPathFactory.newInstance().newXPath();

    try {
      String name = xpath.evaluate("//name", inputSource);
      System.out.println(name);
    } catch (XPathExpressionException e) {
      System.out.println(e.getMessage());
    }
  }
}