Java HTML / XML How to - Get attribute value by element








Question

We would like to know how to get attribute value by element.

Answer

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;
//from w  ww.ja v a2s  .  c  om
import org.w3c.dom.Document;

public class Main {

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document dDoc = builder.parse("input.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    String string = (String) xPath.evaluate(
        "/documents/document/element[@name='doctype']/value", dDoc,
        XPathConstants.STRING);
    System.out.println(string);
  }

}

input.xml

<documents>
  <document>
    <element name="foo">
      <value>FOO</value>
    </element>
    <element name="doctype">
      <value>Circular</value>
    </element>
    <element name="bar">
      <value>BAR</value>
    </element>
  </document>
</documents>