Java HTML / XML How to - Get attribute value from XPath and Element








Question

We would like to know how to get attribute value from XPath and Element.

Answer

import java.io.StringReader;
/* w w  w . j  a va 2  s .c o  m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class Main {

  public static void main(String[] args) throws Exception {
    String xml = "<?xml version='1.0' encoding='UTF-8'?><users><user id='0' firstname='John'/></users>";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new InputSource(new StringReader(xml)));

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    Element userElement = (Element) xpath.evaluate("/users/user", document,
        XPathConstants.NODE);
    System.out.println(userElement.getAttribute("id"));
    System.out.println(userElement.getAttribute("firstname"));
  }

}