How to read/parse XML file in Java?

UPDATED: 07 August 2014
read xml in java

XML stands for Extensible Markup Language. Its goal is to provide generality and simplicity. XML is set of rules to format document that readable by humans and machines both. XMLs are commonly used file format to handle request and response over Internet.

In this example we are using following XML file. We will see how you can parse XML to get multiple nodes and xml node attribute values.
<?xml version="1.0" encoding="UTF-8"?>
  <name>Belgian Waffles</name>
  <price currency="USD" offer="20% Discount">$5.95</price>
  <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
  <restaurant>New York</restaurant>
  <restaurant>Los Angeles</restaurant>
  <name>Strawberry Belgian Waffles</name>
  <price currency="USD" offer="20% Discount">$7.95</price>
  <description>Light Belgian waffles covered with strawberries and whipped cream</description>
  <restaurant>Los Angeles</restaurant>
  <restaurant>Las Vegas</restaurant>
  <name>Berry-Berry Belgian Waffles</name>
  <price currency="USD" offer="10% Discount">$8.95</price>
  <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
  <restaurant>Las Vegas</restaurant>
  <name>French Toast</name>
  <price currency="USD">$4.50</price>
  <description>Thick slices made from our homemade sourdough bread</description>
  <restaurant>Las Vegas</restaurant>
  <name>Homestyle Breakfast</name>
  <price currency="USD">$6.95</price>
  <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
  <restaurant>Las Vegas</restaurant>
  <restaurant>New Jersey</restaurant>

Source Code
Un-comment doc = db.parse(new URL("xml_url").openStream()); to read XML from Internet.
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

public class ReadXML {

    public static void main(String[] args) {
        try {
            File xmlFile = new File("D:\\Dropbox\\Workspace\\SampleXMLFile.xml");
            /* XML Parser base classes */
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = null;
            /* Check if file is exists or not */
            if (xmlFile.exists()) {
                /* Check you have permission to read file or not */
                if (xmlFile.canRead()) {
                    /* Parse XML file from local drive*/
                    doc = db.parse(xmlFile);
                    /* Read XML file from URL */
                    /* doc = db.parse(new URL("xml_url").openStream()); */
                    /* Get all "food" node from XML */
                    NodeList listRootNode = doc.getElementsByTagName("food");

                    /* Loop through all "food" node */
                    for (int i = 0; i < listRootNode.getLength(); i++) {
                        /* Get element from list */
                        Element nodeElement = (Element) listRootNode.item(i);
                        /* Get child node of "food" by its node name */
                        String Foodname = nodeElement.getElementsByTagName("name").item(0).getTextContent();
                        System.out.println("Name: "+Foodname);
                        /* Get child node of "food" by its node name */
                        String FoodPrice = nodeElement.getElementsByTagName("price").item(0).getTextContent();
                        /* Get attribute of node */
                        NamedNodeMap nodeAttributes = nodeElement.getElementsByTagName("price").item(0).getAttributes();
                        System.out.print("Price: "+FoodPrice);
                        if(nodeAttributes != null){
                            if(nodeAttributes.getNamedItem("currency") != null){
                                /* Get attribute value */
                                System.out.print(" Currency: "+nodeAttributes.getNamedItem("currency").getNodeValue());                                 
                            if(nodeAttributes.getNamedItem("offer") != null){
                                /* Get attribute value */
                                System.out.print(" Offer: "+nodeAttributes.getNamedItem("offer").getNodeValue());   
                        /* Get child node of "food" by its node name */
                        String FoodDescription = nodeElement.getElementsByTagName("description").item(0).getTextContent();
                        System.out.println("Description: "+FoodDescription);
                        /* Get child node of "food" by its node name */
                        String FoodCalories = nodeElement.getElementsByTagName("calories").item(0).getTextContent();
                        System.out.println("Calories: "+FoodCalories);
                        /* Get same name child node of "food" by its node name */
                        NodeList listRestaurant = nodeElement.getElementsByTagName("restaurant");
                        for (int j = 0; j < listRestaurant.getLength(); j++) {
                            String city = listRestaurant.item(j).getTextContent();
                            System.out.println("City: "+city);
                } else {
                    /* Show message you don't have permission to read the file */
                    System.out.println("Don't have permission to read the file.");
            } else {
                /* Show message file doesn't exsists the specified location. */
                System.out.println("Can't find file specified");
        } catch (Exception ex) {

Name: Belgian Waffles
Price: $5.95 Currency: USD Offer: 20% Discount
Description: Two of our famous Belgian Waffles with plenty of real maple syrup
Calories: 650
City: New York
City: Los Angeles

Other References:
How to read file in Java?
How to write file in Java?
How to append text to an existing file in Java?