Java HTML / XML How to - Retrieve XML Data








Question

We would like to know how to Retrieve XML Data.

Answer

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/*from  w ww .  j a v a  2  s.c  om*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("data.xml");
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getElementsByTagName("staff");

    if (nl != null && nl.getLength() > 0) {
      for (int i = 0; i < nl.getLength(); i++) {
        // get the employee element
        Element el = (Element) nl.item(i);
        String firstname = getTextValue(el, "firstname");
        String lastname = getTextValue(el, "lastname");
        String nickname = getTextValue(el, "nickname");
        int salary = getIntValue(el, "salary");

        System.out.println(firstname);
        System.out.println(lastname);
        System.out.println(nickname);
        System.out.println(salary);
      }
    }
  }
  private static String getTextValue(Element ele, String tagName) {
    String textVal = null;
    NodeList nl = ele.getElementsByTagName(tagName);
    if (nl != null && nl.getLength() > 0) {
      Element el = (Element) nl.item(0);
      textVal = el.getFirstChild().getNodeValue();
    }
    return textVal;
  }
  private static int getIntValue(Element ele, String tagName) {
    return Integer.parseInt(getTextValue(ele, tagName));
  }
}