Java HTML / XML How to - Read in an XML file








Question

We would like to know how to read in an XML file.

Answer

import java.io.File;
/*  ww  w.  j  ava 2 s.  c o m*/
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 fXmlFile = new File("data.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    doc.getDocumentElement().normalize();
    System.out.println("Root element :"
        + doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("staff");
    for (int temp = 0; temp < nList.getLength(); temp++) {
      Node nNode = nList.item(temp);
      System.out.println("\nCurrent Element :" + nNode.getNodeName());
      if (nNode.getNodeType() == Node.ELEMENT_NODE) {
        Element eElement = (Element) nNode;
        System.out.println("Staff id : " + eElement.getAttribute("id"));
        System.out.println("First Name : "
            + eElement.getElementsByTagName("firstname").item(0)
                .getTextContent());
        System.out.println("Last Name : "
            + eElement.getElementsByTagName("lastname").item(0)
                .getTextContent());
        System.out.println("Nick Name : "
            + eElement.getElementsByTagName("nickname").item(0)
                .getTextContent());
        System.out.println("Salary : "
            + eElement.getElementsByTagName("salary").item(0).getTextContent());
      }
    }
  }
}

data.xml

<?xml version="1.0"?>
<company>
    <staff id="1001">
        <firstname>A</firstname>
        <lastname>B</lastname>
        <nickname>X</nickname>
        <salary>1</salary>
    </staff>
    <staff id="2001">
        <firstname>C</firstname>
        <lastname>D</lastname>
        <nickname>E</nickname>
        <salary>2</salary>
    </staff>
</company>