Java HTML / XML How to - Get the value of a specific XML tag








Question

We would like to know how to get the value of a specific XML tag.

Answer

import java.io.StringReader;
/*w  ww .jav a2  s  .c om*/
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

public class Main {

  private static final String XML = "<dennis><hair>brown</hair><pants>blue</pants><gender>male</gender></dennis>";

  public static void main(String[] args) throws Exception {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xPath = xpf.newXPath();

    InputSource inputSource = new InputSource(new StringReader(XML));
    String result = (String) xPath.evaluate("//gender", inputSource,
        XPathConstants.STRING);
    System.out.println(result);
  }

}