Java HTML / XML How to - Parse XML and get value from attribute








Question

We would like to know how to parse XML and get value from attribute.

Answer

/*from  w  w  w  .  j a  v a2 s  .  c o m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {

  public static void main(String argv[]) throws Exception {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory
        .newDocumentBuilder();
    Document document = documentBuilder.parse(Main.class.getResourceAsStream("/foo.xml"));
    NodeList nodeNodeList = document.getElementsByTagName("node");
    for (int i = 0; i < nodeNodeList.getLength(); i++) {
      Node nNode = nodeNodeList.item(i);
      System.out.println(nNode.getAttributes().getNamedItem("lat")
          .getNodeValue());
      System.out.println(nNode.getAttributes().getNamedItem("lon")
          .getNodeValue());
    }
  }
}