Java HTML / XML How to - Retrieve data out of XML by key








Question

We would like to know how to retrieve data out of XML by key.

Answer

import java.io.StringReader;
//from w  w w.  j  a  v  a  2 s  .  com
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 String XML = "<APP START='2014-08-25 13:45:58' "
      + "SINCE='2016-08-25 13:45:58' " + "STATE='Running' " + "NAME='abc' "
      + "ID='4305' " + "Codebase='www.java2s.com' " + "Build-Revision='123' "
      + "Build-Label='128.3'></APP>";

  public static void main(String[] args) throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    InputSource xml = new InputSource(new StringReader(XML));
    String result = (String) xpath.evaluate("//@Build-Label", xml,
        XPathConstants.STRING);
    System.out.println(result);
  }

}