How to read XML file in Java – (DOM Parser)

In this tutorial, we will show you how to read an XML file via DOM XML parser. DOM parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.

In short, it turns a XML file into DOM or Tree structure, and you have to traverse a node by node to get what you want.

What is Node?
In the DOM, everything in an XML document is a node, read this.
Warning
DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. Please consider SAX parser as solution for it, SAX is faster than DOM and use less memory.

1. DOM XML Parser Example

This example shows you how to get the node by “name”, and display the value.

/Users/mkyong/staff.xml
<?xml version="1.0"?>
<company>
	<staff id="1001">
		<firstname>yong</firstname>
		<lastname>mook kim</lastname>
		<nickname>mkyong</nickname>
		<salary>100000</salary>
	</staff>
	<staff id="2001">
		<firstname>low</firstname>
		<lastname>yin fong</lastname>
		<nickname>fong fong</nickname>
		<salary>200000</salary>
	</staff>
</company>
ReadXMLFile.java
package com.mkyong.seo;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
 
public class ReadXMLFile {
 
  public static void main(String argv[]) {
 
    try {
 
	File fXmlFile = new File("/Users/mkyong/staff.xml");
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(fXmlFile);
 
	//optional, but recommended
	//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
	doc.getDocumentElement().normalize();
 
	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
 
	NodeList nList = doc.getElementsByTagName("staff");
 
	System.out.println("----------------------------");
 
	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());
 
		}
	}
    } catch (Exception e) {
	e.printStackTrace();
    }
  }
 
}

Result

Root element :company
----------------------------
 
Current Element :staff
Staff id : 1001
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
 
Current Element :staff
Staff id : 2001
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000

2. Looping the Node

This example reads the same “staff.xml“, and showing you how to loop the node one by one, and print out the node name and value, and also the attribute if any.

ReadXMLFile2.java
package com.mkyong.seo;
 
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
public class ReadXMLFile2 {
 
  public static void main(String[] args) {
 
    try {
 
	File file = new File("/Users/mkyong/staff.xml");
 
	DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
                             .newDocumentBuilder();
 
	Document doc = dBuilder.parse(file);
 
	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
 
	if (doc.hasChildNodes()) {
 
		printNote(doc.getChildNodes());
 
	}
 
    } catch (Exception e) {
	System.out.println(e.getMessage());
    }
 
  }
 
  private static void printNote(NodeList nodeList) {
 
    for (int count = 0; count < nodeList.getLength(); count++) {
 
	Node tempNode = nodeList.item(count);
 
	// make sure it's element node.
	if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
 
		// get node name and value
		System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
		System.out.println("Node Value =" + tempNode.getTextContent());
 
		if (tempNode.hasAttributes()) {
 
			// get attributes names and values
			NamedNodeMap nodeMap = tempNode.getAttributes();
 
			for (int i = 0; i < nodeMap.getLength(); i++) {
 
				Node node = nodeMap.item(i);
				System.out.println("attr name : " + node.getNodeName());
				System.out.println("attr value : " + node.getNodeValue());
 
			}
 
		}
 
		if (tempNode.hasChildNodes()) {
 
			// loop again if has child nodes
			printNote(tempNode.getChildNodes());
 
		}
 
		System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");
 
	}
 
    }
 
  }
 
}

Result :

Root element :company
 
Node Name =company [OPEN]
Node Value =
 
		yong
		mook kim
		mkyong
		100000
 
 
		low
		yin fong
		fong fong
		200000
 
 
 
Node Name =staff [OPEN]
Node Value =
		yong
		mook kim
		mkyong
		100000
 
attr name : id
attr value : 1001
 
Node Name =firstname [OPEN]
Node Value =yong
Node Name =firstname [CLOSE]
 
Node Name =lastname [OPEN]
Node Value =mook kim
Node Name =lastname [CLOSE]
 
Node Name =nickname [OPEN]
Node Value =mkyong
Node Name =nickname [CLOSE]
 
Node Name =salary [OPEN]
Node Value =100000
Node Name =salary [CLOSE]
Node Name =staff [CLOSE]
 
Node Name =staff [OPEN]
Node Value =
		low
		yin fong
		fong fong
		200000
 
attr name : id
attr value : 2001
 
Node Name =firstname [OPEN]
Node Value =low
Node Name =firstname [CLOSE]
 
Node Name =lastname [OPEN]
Node Value =yin fong
Node Name =lastname [CLOSE]
 
Node Name =nickname [OPEN]
Node Value =fong fong
Node Name =nickname [CLOSE]
 
Node Name =salary [OPEN]
Node Value =200000
Node Name =salary [CLOSE]
Node Name =staff [CLOSE]
Node Name =company [CLOSE]
Note
You may interest at this How to get Alexa Ranking In Java. It shows you how to use DOM to parse the Alexa XML result.

References

  1. When to Use DOM
  2. Normalization in DOM parsing with java – how does it work?
  3. Learn XML DOM
  4. What is Node?
  5. What is Element?
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • ajay

    how to read xml file data that is placed in remote server such that we know the url
    and it is also admin and password protected

    give some soluction

  • Ram

    Hi. I am having XML structure as like you. How to handle null pointer exception when there is no field “firstname” in the xml ?

  • Ram

    Hi. I am having XML structure as like you. How to handle null pointer exception when no is there in one iteration ?

  • mingrui

    This is really helpful and works very well.
    Thank you so much!

  • Pingback: Java XML Tutorial | Dev Solver()

  • Pingback: How to count the depth of xml document (DOM example)()

  • Peter

    Thank you for the great explanation. Really help me a lot understanding the creation of reuse of a xml file in Java.

    Following your example from creating to reading a xml file I think I found some inconsistency.

    In the creating code you are doing this:

    // staff elements
    Element staff = doc.createElement(“Staff”);
    rootElement.appendChild(staff);

    But the xml reader class searches fpr attribute like this:

    // searches for “Staff” instead of “staff”
    NodeList nList = doc.getElementsByTagName(“staff”);

    In my opinion you should change that as it cost me some time to find that little difference.

    Anyways, thank you very much.

  • Pingback: parse String to XML | Coisas de software()

  • rahul

    i had changed position of the code

    if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

    // get node name and value
    System.out.println(“\nNode Name =” + tempNode.getNodeName() + ” [OPEN]”+tempNode.hasChildNodes());
    if (tempNode.hasChildNodes()) {

    // loop again if has child nodes
    printNote(tempNode.getChildNodes());

    }
    System.out.println(“Node Value =” + tempNode.getTextContent());
    }
    my xml is

    myPublication0
    myPublication my book
    myPublication1
    myPublication2 my book2asd

    I got output like this

    Node Name =book [OPEN]true

    Node Name =Publication [OPEN]true
    Node Value = myPublication0
    Node Name =Publication [CLOSE]

    Node Name =Publication [OPEN]true

    Node Name =bookName [OPEN]true
    Node Value = my book
    Node Name =bookName [CLOSE]
    Node Value = myPublication my book
    Node Name =Publication [CLOSE]

    Node Name =Publication [OPEN]true
    Node Value = myPublication1
    Node Name =Publication [CLOSE]

    Node Name =Publication [OPEN]true

    Node Name =bookName [OPEN]true
    Node Value = my book2
    Node Name =bookName [CLOSE]
    Node Value = myPublication2 my book2asd
    Node Name =Publication [CLOSE]
    Node Value =
    myPublication0
    myPublication my book
    myPublication1
    myPublication2 my book2asd

    Node Name =book [CLOSE]
    and i am looking for this

    Node Name =book [OPEN]true

    Node Name =Publication [OPEN]true
    Node Value = myPublication0
    Node Name =Publication [CLOSE]

    Node Name =Publication [OPEN]true
    Node Value = myPublication
    Node Name =bookName [OPEN]true
    Node Value = my book
    Node Name =bookName [CLOSE]

    Node Name =Publication [CLOSE]

    Node Name =Publication [OPEN]true
    Node Value = myPublication1
    Node Name =Publication [CLOSE]

    Node Name =Publication [OPEN]true
    Node Value =myPublication2
    Node Name =bookName [OPEN]true
    Node Value = my book2
    Node Name =bookName [CLOSE]
    Node Value = asd
    Node Name =Publication [CLOSE]

    Node Name =book [CLOSE]

  • rahul

    http://www.daniweb.com/software-development/java/threads/453086/read-xml
    also please tell me the solution related to above problem

  • rahul

    nice tutorial Mr. yong
    why we use if (tempNode.getNodeType() == Node.ELEMENT_NODE) and what is purpose of tempNode.getNodeType().I am asking this question because when if print tempNode.getNodeType() i will get numeric one(1)
    thanks

  • TukTuk

    I am able to resolve the error by header information.

    connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod(“GET”);
    connection.setRequestProperty(“Host”, “www.gulfair.com”);
    connection.setRequestProperty(“Accept”, “text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8″);
    connection.setRequestProperty(“User-Agent”, ” Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0″);
    connection.setUseCaches (false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    //parse using builder to get DOM representation of the XML file
    Document dom = db.parse(connection.getInputStream());

  • TukTuk

    Hi,

    Please help.

    While parsing XML is am getting http 403 error in response, but I am able to access URL on browser.

    • TukTuk

      Getting below error
      “java.io.IOException: Server returned HTTP response code: 403 for URL”

  • pMalik

    Im stuck with this weird issue.

    while running the above code for looping a node i get this head scratching error

    java.lang.NoSuchMethodError: org.w3c.dom.Node.getTextContent()Ljava/lang/String;

    Please reply if you can help me.

  • maro

    Thank you for the code. it is so helpful

  • N.Nagaganesh

    Thanks a lot.

  • Pooja

    Thank you soooo much………..

    The code which you have given is so good…

    It helped me a lot…

    Thank you once again….:-) :-) :-) :-)

    • moumen

      This article is really well done ! It helps me a lot

  • ned

    Love your articles, quick easy and no bs. Keep it up

  • vineet kaushik

    Hi Guys,

    Can you please let me know. how is DOM parser with java is different than dome parser with java script??

  • Nikhil

    Thank you very much.

  • Rahul Jawale

    Thanks. A real simple and useful example.

  • anhtt

    Thanks for the tutorial. please help me how to use DOM to parser an UTF-8 XML file?

    • anhtt

      Sorry, I fixed this problem. My UTF-8 XML file is wrong format.

  • http://antoniodanieleblog.blogspot.it AntonioDaniele

    Thanks, very useful piece of code :)

  • Ayu

    The problem come to :

    File fXmlFile = new File(“/c/wamp/www/suivi/content/iphone/listetest.xml”);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    why cant he open my file ?

    • Ayu

      i try with “c:\\listetest.xml” or “/c:/listetest.xml” or c:/listetest.xml” and nothing works, i dont understand, really….

      i have this error :
      Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)

      i am lost, please help me

      • Ayu

        i have finnaly found the problem. i have move the file on the server and i took his url to access to the file. I ran in background the xml and all its ok now.

  • Ayu

    I have a problem with the first example and i dont know why it doesnt work, can you help me please ?

    package jarvis.project;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Element;
    import java.io.File;

    public class essai extends Activity {
    TextView idCli = null;
    TextView nomCli = null;
    TextView emailCli = null;
    TextView mdpCli = null;

    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    idCli = (TextView)findViewById(R.id.idClient);
    nomCli = (TextView)findViewById(R.id.nomClient);
    emailCli = (TextView)findViewById(R.id.emailClient);
    mdpCli = (TextView)findViewById(R.id.mdpClient);

    try
    {
    idCli.setText(“coucou”);
    File fXmlFile = new File(“/c:/wamp/www/suivi/content/iphone/listeClientXML.php”);
    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(“CL_client”);

    System.out.println(“—————————-“);

    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;

    idCli.setText("id "+ eElement.getAttribute("id"));
    nomCli.setText("nom "+ eElement.getElementsByTagName("nomClient").item(0).getTextContent());
    emailCli.setText("email "+ eElement.getElementsByTagName("emailClient").item(0).getTextContent());
    mdpCli.setText("mdp "+ eElement.getElementsByTagName("mdpClient").item(0).getTextContent());
    }
    }

    }
    catch (Exception e)
    {
    idCli.setText("pascoucou");
    e.printStackTrace();
    }
    }
    }

    always he return "pascoucou" and i cant see where is the mistake. can you help me please?

  • Anonymous Please

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    How could we create an object of an abstract class. Because .newInstance() is the method that basically gives you a new instance of DocumentBuilderFactory class.

    Thanks.

  • raju

    give any better example

    • manasa

      yong
      mook kim
      mkyong
      100000

      low
      yin fong
      fong fong
      200000

  • raju

    yong
    mook kim
    mkyong
    100000

    low
    yin fong
    fong fong
    200000

  • Pingback: How to get and store all currency rates from european central bank xml to string array : Android Community - For Application Development()

  • Pingback: How to get Alexa Ranking In Java()

  • Gops

    Excellent stuff deepthi..if you found answer for 2nd xml..kindly update the code

  • Pingback: SAX parsing using XML file in android : Android Community - For Application Development()

  • Suresh

    Thanks..

  • Pingback: Android: Issues parsing XML : Android Community - For Application Development()

  • Android

    I saw that your code works without .normalize() also (See line

    doc.getDocumentElement().normalize();

    ).
    So, why do we need the normalize(); method ? What does this method really do ?
    If you wish, please answer this question (related to your code) also at stack overflow –
    http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work

  • harsha

    NodeList nl = documentobject.getElementsByTagName(“tagname”);
    if(nl != null && nl.getLength() > 0) {
    for(int i = 0 ; i < nl.getLength();i++) {

    Element el = (Element)nl.item(i);
    by this way you can access all elements.

  • http://[email protected] [email protected]

    deepthi your code does not work properly. please check for compilation dependencies

    • Deepthi

      Abhinav,

      My code works fine for the first XML example with no errors at all. But I need help on how to parse the second XML. i.e., i would want to check if a data type is INT. If its is INT, then check if it has a RANGE then parse through tags within

      • Gops

        could u found the solution?

  • Rohan

    With a little code editing I got this to work! Thank you so much! :D

  • Viraj

    Respected sir,
    My XML file contains following data structure.

    123

    x
    y
    z
    a
    b

    When i am trying to red data from Labels node it get read only first node data.
    eg:x

    i have written following cod to read data from xml file
    File fXmlFile = new File(request.getRealPath(“”)
    + “/resources/SubIndicatorTemplate.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());
    // read caption value
    NodeList captionList = doc.getElementsByTagName(“Captions”);
    for (int i = 0; i < captionList.getLength(); i++) {

    Node nNode = captionList.item(i);
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

    Element eElement = (Element) nNode;
    subIndicator.setCaption(getTagValue("Caption", eElement));
    System.out.println(getTagValue("Caption", eElement));
    }
    }
    // read label value
    NodeList labelList = doc.getElementsByTagName("Labels");
    for (int temp = 0; temp < labelList.getLength(); temp++) {
    System.out.println(labelList.getLength());
    Node nNode = labelList.item(temp);
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

    Element eElement = (Element) nNode;
    subIndicator.getLabels()
    .add(getTagValue("Label", eElement));
    System.out.println(getTagValue("Label", eElement));
    }
    }
    return subIndicator;
    } catch (Exception e) {
    e.printStackTrace();
    return subIndicator;
    }

    What changes i have to do here to read all label tag values

  • Deepthi

    Hi,
    The above code was very much useful to me. But, I am struck with one small problem. I am writing a simple code for generating random data. The code takes input from a XML file. Below is my code and XML file. The code searches for tag. if the type is varchar it generates random names, if it is a an Int it generates random numbers.

    &lt;File&gt;
    &lt;Field&gt;
    &lt;Name&gt;Name&lt;/Name&gt;
    &lt;Type&gt;varchar&lt;/Type&gt;
    &lt;/Field&gt;
    &lt;Field&gt;
    &lt;Name&gt;Number&lt;/Name&gt;
    &lt;Type&gt;Int&lt;/Type&gt;
    &lt;/Field&gt;
    &lt;Field&gt;
    &lt;Name&gt;EmailId&lt;/Name&gt;
    &lt;Type&gt;Email&lt;/Type&gt;
    &lt;/Field&gt;
    &lt;Field&gt;
    &lt;Name&gt;DOB&lt;/Name&gt;
    &lt;Type&gt;Date&lt;/Type&gt;
    &lt;/Field&gt;
    &lt;/File&gt;

    Java code:

    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Element;
    import java.io.File;
     
    public class Testing2 {
     
     
     public static void main(String[] args)
     {
    	try 
    	{
     
    		    File fXmlFile = new File(&quot;test3.xml&quot;);
    		    java.io.FileWriter newFile1;
    		    newFile1 = new FileWriter(&quot;/isac/code/Test/data1.txt&quot;,false);
    		    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    		    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    		    Document doc = dBuilder.parse(fXmlFile);
    		    doc.getDocumentElement().normalize();
     		    System.out.println(&quot;Root element :&quot; + doc.getDocumentElement().getNodeName());
     
    		    NodeList nList = doc.getElementsByTagName(&quot;Field&quot;);
    		    System.out.println(&quot;-----------------------&quot;);
     
    		    int noOfLines = Integer.parseInt(args[0]);
    		   while(noOfLines-- &gt; 0)
    			{
     
    				for (int temp = 0; temp &lt; nList.getLength(); temp++)
    		   		{
     
           					Node nNode = nList.item(temp);	    
    		      		 	if (nNode.getNodeType() == Node.ELEMENT_NODE) 
    					{ 
    		         		 Element eElement = (Element) nNode;
    					 String X = getTagValue(&quot;Type&quot;,eElement);
     
    					switch(X)
    					{
    					case &quot;Int&quot;:	 					
    					String rev = Integer.toString(getRandomInteger(1, 10000));					
    					newFile1.write(rev + &quot;\t&quot;);
    					break;
     
    					case &quot;varchar&quot;:
    					String rev1 = getRandomName(1, 28);					
    					newFile1.write(getRandomName(1, 28)+ &quot;\t&quot;);
    					break;
     
    					case &quot;Date&quot;:
    					newFile1.write(getRandomDate()+ &quot;\n&quot;);
    					break;
    					case &quot;Email&quot;:
    					newFile1.write(getRandomEmail()+ &quot;\n&quot;);
    					break;
     
    					default:
    					System.out.println(&quot;No&quot;);
    					break;
     
    					}
    				}
    			}
    		}
    				newFile1.flush();
    				newFile1.close();
    	}
     
    catch(Exception exp)
    		{
    			System.out.println(exp);
    		}
     
     }
     
    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();    
     }
    public static int getRandomInteger(int minValue, int maxValue)
    	{
    		double random = Math.random();
    		int ret = (int)((maxValue - minValue) * random) + minValue;
    		return ret;
    	}
    public static String getRandomName(int minValue, int maxValue)
    	{
    		List&lt;String&gt; names = new ArrayList&lt;String&gt;();
    		names.add(&quot;John Doe&quot;);
    		names.add(&quot;Jane Doe&quot;);
    		names.add(&quot;Dick Doe&quot;);
    		names.add(&quot;Harry Doe&quot;);
    		names.add(&quot;Sally Doe&quot;);
    		names.add(&quot;Koli Doe&quot;);
    		names.add(&quot;Doni Doe&quot;);
    		names.add(&quot;Tendy Doe&quot;);
    		names.add(&quot;Sammy Doe&quot;);
    		names.add(&quot;Virendra Doe&quot;);
    		names.add(&quot;Gambhir Doe&quot;);
    		names.add(&quot;James Doe&quot;);
    		names.add(&quot;Jai Doe&quot;);
    		names.add(&quot;Jeff Doe&quot;);
    		names.add(&quot;Shiv Doe&quot;);
    		names.add(&quot;Sam Doe&quot;);
    		names.add(&quot;Sandy Doe&quot;);
    		names.add(&quot;Sid Doe&quot;);
    		names.add(&quot;Kelly Doe&quot;);
    		names.add(&quot;Lara Doe&quot;);
    		names.add(&quot;Nandi Doe&quot;);
    		names.add(&quot;Robin Doe&quot;);
    		names.add(&quot;Ria Doe&quot;);
    		names.add(&quot;Ram Doe&quot;);
    		names.add(&quot;Edwin Doe&quot;);
    		names.add(&quot;Kelvin Doe&quot;);
    		names.add(&quot;Phillip Doe&quot;);
    		names.add(&quot;Robort Doe&quot;);
    		double random = Math.random();
    		int ret = (int)((maxValue - minValue) * random) + minValue;
    		return names.get(ret);
    	}
    private static String getRandomDate()
    {
     
        Calendar dob = Calendar.getInstance();
     
        int year = (int)(Math.random() * 25) + 25;
        int date = (int)(Math.random() * 28) + 25;
        int month = (int)(Math.random() * 12) + 12;
     
     
        dob.roll(Calendar.YEAR, -year);
        dob.roll(Calendar.MONTH, -month);
        dob.roll(Calendar.DAY_OF_MONTH, -date);
        StringBuffer sb = new StringBuffer();
        sb.append(dob.get(Calendar.YEAR)).append(&quot;/&quot;).append(dob.get(Calendar.MONTH)+1).append(&quot;/&quot;).append(dob.get(Calendar.DAY_OF_MONTH));
        return sb.toString();
    }
     
    private static String getRandomEmail()
    {
    	String name = getRandomName(1,28);
    	return getRandomName(1,28) + getRandomInteger(1,500) +&quot;@gmail.com&quot;;
    }
     
    }

    Above code works fine for the XML.
    Now, I have another XML file,

    &lt;File&gt;
    &lt;Field&gt;
    &lt;Name&gt;Name&lt;/Name&gt;
    &lt;Type&gt;varchar&lt;/Type&gt;
    &lt;/Field&gt;
    &lt;Field&gt;
    &lt;Name&gt;Number&lt;/Name&gt;
    &lt;Type&gt;Int&lt;/Type&gt;
    &lt;/Field&gt;
    &lt;Field&gt;
    &lt;Name&gt;Number Range&lt;/Name&gt;
    &lt;Type&gt;Int&lt;/Type&gt;
    &lt;Range&gt;
    	&lt;Type&gt;MinMax&lt;/Type&gt;
    	&lt;Min&gt;20&lt;/Min&gt;
    	&lt;Max&gt;45&lt;/Max&gt;
    &lt;/Range&gt;
    &lt;/Field&gt;
    &lt;Field&gt;
    &lt;Name&gt;EmailId&lt;/Name&gt;
    &lt;Type&gt;Email&lt;/Type&gt;
    &lt;/Field&gt;
    &lt;Field&gt;
    &lt;Name&gt;DOB&lt;/Name&gt;
    &lt;Type&gt;Date&lt;/Type&gt;
    &lt;/Field&gt;
    &lt;/File&gt;

    I want to check if the type is “Int”, then want to check if its a range of numbers. if it has a then generate random numbers taking the values within and tags. Please help me get parse through tags within tags.

  • Sathishkumar

    Hi, I am using large size xml, which has 400 records. Its format is

    abskdfjk
    18-07-2012 13:18
    ——
    *******

    SWTKLWPEMLLQ
    18-07-2012 13:43
    ———
    ***********

    This is sample. I want to parse xml based on the datetime value. How to check this in XMLPullParser?

  • Muhammad Ahmed

    Thanks for this nice explanation about reading XML file. My problem is that: I have to read different xml files from a specific folder. How can i do this?.

    Thanks alot.

  • Mike

    This is by far the easiest XML reader code i have been able to locate. It worked well for my needs.

  • Sridhar Prabhakar

    Thanks for the tutorial. I improved a bit on this and wrote an entire utility class to handle XML files.

    http://sridharprabhakartechramblings.blogspot.in/2012/10/xml-parsing-made-easy.html

  • Malay Nayak

    I am no getting properly it please explain.
    Why it shows null when i write ” Node nValue=eElement.getElementsByTagName(sTag).item(0);”

    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();
    }

  • Christos

    Nice work but is there any way to read files in utf-8 encoding because i have problem with it…

    Thanx a lot!

  • Hiren Manek

    what is use of following line?
    “doc.getDocumentElement().normalize();”

    • Android

      good one. code works without normalize also. see my question.

  • Eric

    HI,

    Please how to parse file XMI with DOM?

    Thank you for help

  • http://wikiknowledgee.com wikiknowledgee

    nice article. thankx author

  • Pingback: How to parse complex xml data | Jisku.com - Developers Network()