Java HTML / XML How to - Read any XML file and get tag value








Question

We would like to know how to read any XML file and get tag value.

Answer

import java.io.File;
/*from   www .  j  a  v a 2 s  . c  om*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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

public class Main {

  public static void main(String argv[]) throws Exception {
    File myfile = new File("data.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(myfile);
    doc.getDocumentElement().normalize();

    System.out.println("Root element :"
        + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("test");
    for (int temp = 0; temp < nList.getLength(); temp++) {
      Node nNode = nList.item(temp);
      if (nNode.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) nNode;
        System.out.println("First Name : " + getTagValue("id", eElement));
        System.out.println("Last Name : " + getTagValue("result", eElement));
      }
    }
  }
  private static String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
        .getChildNodes();
    Node nValue = (Node) nlList.item(0);
    return nValue.getNodeValue();
  }
}