Java HTML / XML How to - Retrieve/extract XML element attribute value








Question

We would like to know how to retrieve/extract XML element attribute value.

Answer

import java.io.FileInputStream;
import java.io.InputStream;
/*from   w ww  .ja v  a2s.  com*/
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

public class Main {

  public static void main(String[] args) throws Exception {
    InputStream inputStream = new FileInputStream("data.xml");
    InputSource inputSource = new InputSource(inputStream);
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("/PaymentElement/Payment/@seqID");
    Object result = expr.evaluate(inputSource, XPathConstants.STRING);
    System.out.println(result);
  }

}