Java HTML / XML How to - Find the value of a specific attribute in an XML file in java








Question

We would like to know how to find the value of a specific attribute in an XML file in java.

Answer

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
//from w w w  . j av a  2  s  .  c  o m
import org.w3c.dom.Document;

public class Main {
    public static void main(String[] args) throws Exception {
        XPath xpath = XPathFactory.newInstance().newXPath();
        Document doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse("file:////tmp/whatever.xml");
        String version = xpath.evaluate("//behavior/@version", doc);
        System.out.println(version);
    }
}