XML and Java - Parsing XML using Java Tutorial

By: totheriver.com Emailed: 1676 times Printed: 2158 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Parsing XML
If you are a beginner to XML using Java then this is the perfect sample to parse a XML file create Java Objects and manipulate them.

The idea here is to parse the employees.xml file with content as below

<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
  <Employee type="permanent">
        <Name>Seagull</Name>
        <Id>3674</Id>
        <Age>34</Age>
   </Employee>
  <Employee type="contract">
        <Name>Robin</Name>
        <Id>3675</Id>
        <Age>25</Age>
    </Employee>
  <Employee type="permanent">
        <Name>Crow</Name>
        <Id>3676</Id>
        <Age>28</Age>
    </Employee>
</Personnel>

From the parsed content create a list of Employee objects and print it to the console. The output would be something like


Employee Details - Name:Seagull, Type:permanent, Id:3674, Age:34.
Employee Details - Name:Robin, Type:contract, Id:3675, Age:25.
Employee Details - Name:Crow, Type:permanent, Id:3676, Age:28.
We will start with a DOM parser to parse the xml file, create Employee value objects and add them to a list. To ensure we parsed the file correctly let's iterate through the list and print the employees data to the console. Later we will see how to implement the same using SAX parser.
In a real world situation you might get a xml file from a third party vendor which you need to parse and update your database.

Using DOM
    This program DomParserExample.java uses DOM API.

The steps are

  • Get a document builder using document builder factory and parse the xml file to create a DOM object
  • Get a list of employee elements from the DOM
  • For each employee element get the id, name, age and type. Create an employee value object and add it to the list.
  • At the end iterate through the list and print the employees to verify we parsed it right.

a) Getting a document builder

	private void parseXmlFile(){
		//get the factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try {

			//Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();

			//parse using builder to get DOM representation of the XML file
			dom = db.parse("employees.xml");


		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}

b) Get a list of employee elements
Get the rootElement from the DOM object.From the root element get all employee elements. Iterate through each employee element to load the data.


	private void parseDocument(){
		//get the root element
		Element docEle = dom.getDocumentElement();

		//get a nodelist of 
 elements
		NodeList nl = docEle.getElementsByTagName("Employee");
		if(nl != null && nl.getLength() > 0) {
			for(int i = 0 ; i < nl.getLength();i++) {

				//get the employee element
				Element el = (Element)nl.item(i);

				//get the Employee object
				Employee e = getEmployee(el);

				//add it to list
				myEmpls.add(e);
			}
		}
	}

c) Reading in data from each employee.


	/**
	 * I take an employee element and read the values in, create
	 * an Employee object and return it
	 */
	private Employee getEmployee(Element empEl) {

		//for each <employee> element get text or int values of
		//name ,id, age and name
		String name = getTextValue(empEl,"Name");
		int id = getIntValue(empEl,"Id");
		int age = getIntValue(empEl,"Age");

		String type = empEl.getAttribute("type");

		//Create a new Employee with the value read from the xml nodes
		Employee e = new Employee(name,id,age,type);

		return e;
	}


	/**
	 * I take a xml element and the tag name, look for the tag and get
	 * the text content
	 * i.e for <employee><name>John</name></employee> xml snippet if
	 * the Element points to employee node and tagName is 'name' I will return John
	 */
	private 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;
	}


	/**
	 * Calls getTextValue and returns a int value
	 */
	private int getIntValue(Element ele, String tagName) {
		//in production application you would catch the exception
		return Integer.parseInt(getTextValue(ele,tagName));
	}

d) Iterating and printing.


	private void printData(){

		System.out.println("No of Employees '" + myEmpls.size() + "'.");

		Iterator it = myEmpls.iterator();
		while(it.hasNext()) {
			System.out.println(it.next().toString());
		}
	}

Using SAX
This program SAXParserExample.java parses a XML document and prints it on the console.
Sax parsing is event based modelling.When a Sax parser parses a XML document and every time it encounters a tag it calls the corresponding tag handler methods

when it encounters a Start Tag it calls this method
    public void startElement(String uri,..

when it encounters a End Tag it calls this method
    public void endElement(String uri,...

Like the dom example this program also parses the xml file, creates a list of employees and prints it to the console. The steps involved are

  • Create a Sax parser and parse the xml
  • In the event handler create the employee object
  • Print out the data
Basically the class extends DefaultHandler to listen for call back events. And we register this handler with the Sax parser to notify us of call back events. We are only interested in start event, end event and character event.
In start event if the element is employee we create a new instant of employee object and if the element is Name/Id/Age we initialize the character buffer to get the text value.
In end event if the node is employee then we know we are at the end of the employee node and we add the Employee object to the list.If it is any other node like Name/Id/Age we call the corresponding methods like setName/SetId/setAge on the Employee object.
In character event we store the data in a temp string variable.

a) Create a Sax Parser and parse the xml


	private void parseDocument() {

		//get a factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {

			//get a new instance of parser
			SAXParser sp = spf.newSAXParser();

			//parse the file and also register this class for call backs
			sp.parse("employees.xml", this);

		}catch(SAXException se) {
			se.printStackTrace();
		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch (IOException ie) {
			ie.printStackTrace();
		}
	}

b) In the event handlers create the Employee object and call the corresponding setter methods.


	//Event Handlers
	public void startElement(String uri, String localName, String qName,
		Attributes attributes) throws SAXException {
		//reset
		tempVal = "";
		if(qName.equalsIgnoreCase("Employee")) {
			//create a new instance of employee
			tempEmp = new Employee();
			tempEmp.setType(attributes.getValue("type"));
		}
	}


	public void characters(char[] ch, int start, int length) throws SAXException {
		tempVal = new String(ch,start,length);
	}

	public void endElement(String uri, String localName,
		String qName) throws SAXException {

		if(qName.equalsIgnoreCase("Employee")) {
			//add it to the list
			myEmpls.add(tempEmp);

		}else if (qName.equalsIgnoreCase("Name")) {
			tempEmp.setName(tempVal);
		}else if (qName.equalsIgnoreCase("Id")) {
			tempEmp.setId(Integer.parseInt(tempVal));
		}else if (qName.equalsIgnoreCase("Age")) {
			tempEmp.setAge(Integer.parseInt(tempVal));
		}

	}

c) Iterating and printing.


	private void printData(){

		System.out.println("No of Employees '" + myEmpls.size() + "'.");

		Iterator it = myEmpls.iterator();
		while(it.hasNext()) {
			System.out.println(it.next().toString());
		}
	}

Generating XML
    The previous programs illustrated how to parse an existing XML file using both SAX and DOM Parsers.
But generating a XML file from scratch is a different story, for instance you might like to generate a xml file for the data extracted from a database.To keep the example simple this program XMLCreatorExample.java generates XML from a list preloaded with hard coded data. The output will be book.xml file with the following content.


<?xml version="1.0" encoding="UTF-8"?>
<Books>
    <Book Subject="Java 1.5">
        <Author>Kathy Sierra .. etc</Author>
        <Title>Head First Java</Title>
    </Book>
    <Book Subject="Java Architect">
        <Author>Kathy Sierra .. etc</Author>
        <Title>Head First Design Patterns</Title>
    </Book>
</Books>

The steps involved are
  • Load Data
  • Get an instance of Document object using document builder factory
  • Create the root element Books
  • For each item in the list create a Book element and attach it to Books element
  • Serialize DOM to FileOutputStream to generate the xml file "book.xml".

a) Load Data.



	/**
	 * Add a list of books to the list
	 * In a production system you might populate the list from a DB
	 */
	private void loadData(){

		myData.add(new Book("Head First Java",
			"Kathy Sierra .. etc","Java 1.5"));

		myData.add(new Book("Head First Design Patterns",
			"Kathy Sierra .. etc","Java Architect"));
	}

c) Getting an instance of DOM.

	/**
	 * Using JAXP in implementation independent manner create a document object
	 * using which we create a xml tree in memory
	 */
	private void createDocument() {

		//get an instance of factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
		//get an instance of builder
		DocumentBuilder db = dbf.newDocumentBuilder();

		//create an instance of DOM
		dom = db.newDocument();

		}catch(ParserConfigurationException pce) {
			//dump it
			System.out.println("Error while trying to instantiate DocumentBuilder " + pce);
			System.exit(1);
		}

	}

c) Create the root element Books.



	/**
	 * The real workhorse which creates the XML structure
	 */
	private void createDOMTree(){

		//create the root element 

		Element rootEle = dom.createElement("Books");
		dom.appendChild(rootEle);

		//No enhanced for
		Iterator it  = myData.iterator();
		while(it.hasNext()) {
			Book b = (Book)it.next();
			//For each Book object  create 
 element and attach it to root
			Element bookEle = createBookElement(b);
			rootEle.appendChild(bookEle);
		}

	}

d) Creating a book element.

	/**
	 * Helper method which creates a XML element 

	 * @param b The book for which we need to create an xml representation
	 * @return XML element snippet representing a book
	 */
	private Element createBookElement(Book b){

		Element bookEle = dom.createElement("Book");
		bookEle.setAttribute("Subject", b.getSubject());

		//create author element and author text node and attach it to bookElement
		Element authEle = dom.createElement("Author");
		Text authText = dom.createTextNode(b.getAuthor());
		authEle.appendChild(authText);
		bookEle.appendChild(authEle);

		//create title element and title text node and attach it to bookElement
		Element titleEle = dom.createElement("Title");
		Text titleText = dom.createTextNode(b.getTitle());
		titleEle.appendChild(titleText);
		bookEle.appendChild(titleEle);

		return bookEle;

	}

e) Serialize DOM to FileOutputStream to generate the xml file "book.xml".


	/**
	 * This method uses Xerces specific classes
	 * prints the XML document to file.
     */
	private void printToFile(){

		try
		{
			//print
			OutputFormat format = new OutputFormat(dom);
			format.setIndenting(true);

			//to generate output to console use this serializer
			//XMLSerializer serializer = new XMLSerializer(System.out, format);


			//to generate a file output use fileoutputstream instead of system.out
			XMLSerializer serializer = new XMLSerializer(
			new FileOutputStream(new File("book.xml")), format);

			serializer.serialize(dom);

		} catch(IOException ie) {
		    ie.printStackTrace();
		}
	}

Note:
The Xerces internal classes OutputFormat and XMLSerializer are in different packages.

In JDK 1.5 with built in Xerces parser they are under
com.sun.org.apache.xml.internal.serialize.OutputFormat
com.sun.org.apache.xml.internal.serialize.XMLSerializer

In Xerces 2.7.1 which we are using to run these examples they are under
org.apache.xml.serialize.XMLSerializer
org.apache.xml.serialize.OutputFormat
We are using Xerces 2.7.1 with JDK 1.4 and JDK 1.3 as the default parser with JDK 1.4 is Crimson and there is no built in parser with JDK 1.3.
Also please remember it is not advisable to use parser implementation specific classes like OutputFormat and XMLSerializer as they are only available in Xerces and if you switch to another parser in the future you may have to rewrite.

Instructions to run these programs

The instructions to compile and run these programs varies based on the JDK that you are using. This is due to the way the XML parser is bundled with various Java distributions.These instructions are for Windows OS.For Unix or Linux OS you just need to change the folder paths accordingly.

Using JDK 1.5

Xerces parser is bundled with the JDK 1.5 distribution.So you need not download the parser separately.

Running DOMParserExample

  1. Download DomParserExample.java, Employee.java, employees.xml to c:\xercesTest
  2. Go to command prompt and type
    cd c:\xercesTest
  3. To compile, type
    javac -classpath . DomParserExample.java
  4. To run, type
    java -classpath . DomParserExample
Running SAXParserExample
  1. Download SAXParserExample.java, Employee.java, employees.xml to c:\xercesTest
  2. Go to command prompt and type
    cd c:\xercesTest
  3. To compile, type
    javac -classpath . SAXParserExample.java
  4. To run,type
    java -classpath . SAXParserExample
Running XMLCreatorExample
  1. Download XMLCreatorExample.java, Book.java to c:\xercesTest
  2. Go to command prompt and type
    cd c:\xercesTest
  3. To compile, type
    javac -classpath . XMLCreatorExample.java
  4. To run, type
    java -classpath . XMLCreatorExample

 


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(90)


1. View Comment

This tutorial is really good for beginners.It helped me a lot.

View Tutorial          By: Prabhat Kumar at 2007-04-09 05:02:02
2. View Comment

This tutorial is really fantastic.It helped me a lot.

View Tutorial          By: Rakesh Verma at 2008-06-25 13:25:23
3. View Comment

Great one on java-xml binding..

View Tutorial          By: Ranadeep Roy at 2008-07-03 23:15:22
4. View Comment

great work

View Tutorial          By: Dinesh557 at 2008-09-25 00:27:59
5. View Comment

This tutorial is good for beginners. If you provide when we can use SAX & DOM parses and deferens about those then this tutorial is really very good for beginners.

View Tutorial          By: Sateesh Bobby at 2008-12-09 23:56:18
6. View Comment

It was really helpful.... i cleared my lab test with the help of this. Thanks a lot.

View Tutorial          By: kishore at 2009-01-21 22:30:08
7. View Comment

This tutorial is very nice for beginners.

View Tutorial          By: Wakil Ahamad at 2009-02-07 05:58:31
8. View Comment

Hai,
I have stil problem with generate XML prog, when i run the

XMLCreatorExample.java, Book.java

i got the error as
Debugger stopped on uncompilable source code.
I dont understand why it comes.


Can any 1 tell

Thanks
Priyan


View Tutorial          By: Priyan at 2009-04-06 12:08:42
9. View Comment

i found this tutorial very useful... i need to know the differences between Xerces, DOMParser and SAXParser...
please tel me


View Tutorial          By: Anonymous at 2009-04-14 21:09:20
10. View Comment

very good tutorial

View Tutorial          By: Anonymous at 2009-06-13 01:14:25
11. View Comment

This tutorial is very much useful for me to develop java based xml application

View Tutorial          By: R. Lawrance at 2009-07-26 22:03:15
12. View Comment

grt tutorial

View Tutorial          By: sss at 2009-08-30 03:33:13
13. View Comment

i am getting the following error:
cannot find symbol
symbol: Employee


View Tutorial          By: santhosh at 2009-09-24 09:13:57
14. View Comment

Good one.. great for beginners..

View Tutorial          By: varun at 2009-09-29 14:18:04
15. View Comment

Great help

View Tutorial          By: Rajeshvar at 2009-11-04 08:43:09
16. View Comment

Good for Beginners

View Tutorial          By: Srinivasula Reddy at 2009-11-05 02:04:25
17. View Comment

I really thanks to you for providing wonderful information very simply and understandable easily.

View Tutorial          By: Chandra Sekhar Puli at 2009-11-07 04:03:44
18. View Comment

I went befly through this, it is woderful, usefull for all bigners.

I want to suggest you that, it wold be better providing the clear explanation about methods in jave which are used in jave applications to retrive the content from the xml parsers.


View Tutorial          By: Mallikarjuna.N at 2009-11-28 11:41:58
19. View Comment

This example is very good and useful. I request you to include the links to downloads to compile and run the example files. I am thankful to your post and looking for more.

View Tutorial          By: Ambarisha Malladi at 2010-02-10 22:50:38
20. View Comment

Wow Such a good tutorial. It really really make me understand what a parser is and how it reads from a XML document using DOM,SAX parsers.
Many Many Thanks for the author


View Tutorial          By: Anonymous at 2010-02-19 05:53:11
21. View Comment

Very Useful tutorial for beginners.. Thanx

View Tutorial          By: Rohini at 2010-02-23 23:16:16
22. View Comment

The code is really helpfull...
reading or writting XML seems to be very difficult for me earlier...
but explained in good way...thanks


View Tutorial          By: sharda at 2010-03-11 03:28:02
23. View Comment

Very good example with explaination and sample code..
Good Job...it really made simple to know how to read or Write XMl


View Tutorial          By: plenitude at 2010-04-15 23:55:02
24. View Comment

This tutorial is really fantastic.It helped me a lot..............

View Tutorial          By: LakshmiNaryana Gorantla at 2010-04-19 23:35:45
25. View Comment

Buenisimo tutorial, este rebuena la cosa
Gracias!!


View Tutorial          By: Popoca at 2010-04-20 15:50:29
26. View Comment

Thanks to the author, it was really a good tutorial :-)

View Tutorial          By: Ashok Kumar at 2010-04-29 05:54:47
27. View Comment

Thanks a lot :-) It is very informative

View Tutorial          By: praveen at 2010-05-03 22:17:19
28. View Comment

Highly appreciatable.Excellent Docs.

View Tutorial          By: Debi P Naik at 2010-05-04 05:55:45
29. View Comment

really a gud work for xml parsing readers

View Tutorial          By: shreya at 2010-07-02 02:35:04
30. View Comment

Hi
Gr8 work......!!!!
thanks...!!!


View Tutorial          By: Antim Jain at 2010-07-12 23:44:14
31. View Comment

Thanks to you for providing such a wonderful information in very simple manner.

View Tutorial          By: Tara Patra at 2010-08-30 07:22:44
32. View Comment

This is really a tremendous tutorials for the beginners, one who don't know about it much, then he/she should try it yourself, you will definitely realize it.

View Tutorial          By: Raghvendra Dwivedi at 2010-09-01 10:22:42
33. View Comment

really a big salute for this notes

View Tutorial          By: SUNDARARAJ VELUSAMY at 2010-09-14 23:39:48
34. View Comment

Good explanation on how to parse.

You could also provide differences between these two approaches and why should we chose one.

Thanks,
Sravan


View Tutorial          By: Sravan at 2010-10-05 05:16:39
35. View Comment

It is a good tutorial but I think the "Instructions to run these programs" part should be put on top. Some of the problem in the comments can be solved if this was read first.

View Tutorial          By: Jaypee at 2010-10-10 22:40:50
36. View Comment

I've been struggling with this for a while now. The node list generated is null, even using the exact xml from the example. Any ideas???

View Tutorial          By: Deb at 2010-10-14 11:36:33
37. View Comment

Many thanks for this tutorial. Exactly what I was looking for.

View Tutorial          By: Fedor Emelianenko at 2010-10-28 08:01:17
38. View Comment

I have modified this example a bit and I'm using a different xml file. I am getting the following error:

[Fatal Error] subject.xml:4:233: The entity "rsquo" was referenced, but not declared.
org.xml.sax.SAXParseException: The entity "rsquo" was referenced, but not declared.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at DomParserExample2.parseXmlFile(DomParserExample2.java:42)
at DomParserExample2.runExample(DomParserExample2.java:24)
at DomParserExample2.main(DomParserExample2.java:115)
Exception in thread "main" java.lang.NullPointerException
at DomParserExample2.parseDocument(DomParserExample2.java:54)
at DomParserExample2.runExample(DomParserExample2.java:27)
at DomParserExample2.main(DomParserExample2.java:115)


Anyone know how to solve this?


View Tutorial          By: Lee Murray at 2010-11-02 03:41:56
39. View Comment

This is a great tutorial. I have a slight problem, however, when I add entity references in the employees.xml file (for argument's sake consider modifying <Name>Seagull</Name> to <Name>&lt;Seagull/&gt;</Name>) upon parsing the file using SAX; only > gets printed instead of <Seagull/>. How can I resolve this problem?

Thank you.


View Tutorial          By: Vix at 2010-11-22 13:42:03
40. View Comment

Hi,
Its good but you can make it more better if you describe the difference between both the parser as well as define there uses.
Vishakha


View Tutorial          By: vishakha sharma at 2010-12-15 06:14:52
41. View Comment

This is very useful example for beginners.
It would be great if we get some good example code for STAX parser also.


View Tutorial          By: Amresh at 2011-02-28 22:20:11
42. View Comment

It is an excellent article. Please keep up the good work.

View Tutorial          By: sanjay at 2011-03-09 03:17:45
43. View Comment

Excellent article

View Tutorial          By: JJ at 2011-03-21 13:42:35
44. View Comment

Good article..

View Tutorial          By: Sudarshan at 2011-03-28 02:57:53
45. View Comment

This is good for beginners.

View Tutorial          By: sathish at 2011-04-05 11:37:30
46. View Comment

this site and document good for the starter. Thanks.

View Tutorial          By: davit off at 2011-04-17 06:57:02
47. View Comment

I want to parse a xml content some think like below. It is HTML formatted. How can i parse the content?
I want the values like name,employee number ,age etc....
But they are not defined in particular tag.
Kindly help me out in extracting the content from this HTML formatted response.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ListForEmployee_1_0 SYSTEM "c:/file/hello.dtd">
<List suppressFolio="n" xmlProviderInfo="test Server" Strategy="normal">
<Wrapper>
<doc>
<docBody>
<displayGroup lineSeparator="n" leftIndent="10" fontFamily="Verdana" fontSize="11">
Service: <startStyle fontEmphasis="b"/>Employee File<endStyle/> <startStyle fontEmphasis="b"/>10 records<endStyle/>
<newLine n="1"/>
Company: <startStyle fontEmphasis="b"/>A2B company<endStyle/>
</displayGroup>
<displayGroup lineSeparator="y">
<table>
<cellWidth numSpaces="10"/>
<cellWidth numSpaces="2"/>
<cellWidth numSpaces="15"/>
<cellWidth numSpaces="20"/>
<cellWidth numSpaces="20"/>
<cellWidth numSpaces="13"/>
<tableBody>
<row>
<cell topBorder="y" bottomBorder="y" justification="left"><startStyle fontEmphasis="b"/>Name<endStyle/></cell>
<cell topBorder="y" bottomBorder="y">Employee number</cell>
<cell topBorder="y" bottomBorder="y" justification="left"><startStyle fontEmphasis="b"/>Sex<endStyle/></cell>
<cell topBorder="y" bottomBorder="y" justification="left"><startStyle fontEmphasis="b"/>Age<endStyle/></cell>
<cell topBorder="y" bottomBorder="y" justification="left"><startStyle fontEmphasis="b"/>Designation<endStyle/></cell>
<cell topBorder="y" bottomBorder="y" justification="left"><startStyle fontEmphasis="b"/>Date<endStyle/></cell>
</row>

<row>
<cell topBorder="y" bottomBorder="y" justification="left">Mark</cell>
<cell topBorder="y" bottomBorder="y" justification="left">1001</cell>
<cell topBorder="y" bottomBorder="y" justification="left">Male</cell>
<cell topBorder="y" bottomBorder="y" justification="left">25</cell>
<cell topBorder="y" bottomBorder="y" justification="left">Analyst</cell>
<cell topBorder="y" bottomBorder="y" justification="left">2005-02-01</cell>
</row>


<row>
<cell topBorder="y" bottomBorder="y" justification="left">ricky</cell>
<cell topBorder="y" bottomBorder="y" justification="left">1005</cell>
<cell topBorder="y" bottomBorder="y" justification="left">Male</cell>
<cell topBorder="y" bottomBorder="y" justification="left">28</cell>
<cell topBorder="y" bottomBorder="y" justification="left">Analyst</cell>
<cell topBorder="y" bottomBorder="y" justification="left">2008-12-01</cell>
</row>


<row>
<cell topBorder="y" bottomBorder="y" justification="left">David</cell>
<cell topBorder="y" bottomBorder="y" justification="left">1007</cell>
<cell topBorder="y" bottomBorder="y" justification="left">Male</cell>
<cell topBorder="y" bottomBorder="y" justification="left">35</cell>
<cell topBorder="y" bottomBorder="y" justification="left">SeniorAnalyst</cell>
<cell topBorder="y" bottomBorder="y" justification="left">2005-08-11</cell>
</row>


<row>
<cell topBorder="y" bottomBorder="y" justification="left">hilary</cell>
<cell topBorder="y" bottomBorder="y" justification="left">1008</cell>
<cell topBorder="y" bottomBorder="y" justification="left">female</cell>
<cell topBorder="y" bottomBorder="y" justification="left">28</cell>
<cell topBorder="y" bottomBorder="y" justification="left">maketing</cell>
<cell topBorder="y" bottomBorder="y" justification="left">2001-02-01</cell>
</row>

</tableBody>
</table>
</displayGroup>
</docBody>
</doc>
</Wrapper>
</List>


View Tutorial          By: sagar at 2011-04-20 00:59:06
48. View Comment

great work..keep it up.

View Tutorial          By: faizaan at 2011-04-29 12:23:39
49. View Comment

fantastic explaination about XML parsers

View Tutorial          By: smitha at 2011-05-15 04:53:00
50. View Comment

Very usefull tutorial, but I've got a question:
How to detect that an element has a missing closing tag and fix it?
The way you showed how to read doesn't prevent errors like this, any suggestion?


View Tutorial          By: Wolfgang Marcos at 2011-05-16 11:12:19
51. View Comment

As a beggnar, i find it varry varry usefuull.... Pleees includ sum morr examppls so tat i can becume an experrrrt on thiz subjuct......

Thanksss alooootttt...


View Tutorial          By: Rameeza at 2011-05-17 03:14:50
52. View Comment

XML Parsing - Simplified.
Thanks.


View Tutorial          By: Piyush at 2011-05-19 22:56:23
53. View Comment

Hello all,Actually i want xml parser in blackberry anybody plz help

View Tutorial          By: arun at 2011-06-01 06:17:16
54. View Comment

very nice tutorial.
Thanks..


View Tutorial          By: Ramar at 2011-06-16 08:16:14
55. View Comment

very helpful & gud tutorial...
thanks....


View Tutorial          By: Narpinder Sharma at 2011-06-27 03:12:20
56. View Comment

xml response is :

<?xml version="1.0" encoding="UTF-8"?><oas:changeNotificationTriggerStatus xmlns:oas="http://xml.massive.com.au/bt/oas/api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xml.massive.com.au/bt/oas/api oas_changeNotificationTriggerStatusRequest3.0 v2.xsd "><numberOfResultsReturned>1</numberOfResultsReturned><triggerStateResults> <triggerStateResult> <triggerDocId>1234</triggerDocId> <triggerReference>1234</triggerReference> <changeReasonCode>5105</changeReasonCode> <changeReasonDescription>No notification trigger found: [triggerReference : 1234]</changeReasonDescription> <changeAction>disable</changeAction> <triggerStateBefore></triggerStateBefore> <triggerStateAfter></triggerStateAfter> <changeDateTime>2011-06-29T07:04:30</changeDateTime> </triggerStateResult> <triggerStateResult> <triggerDocId>1236</triggerDocId> <triggerReference>1236</triggerReference> <changeReasonCode>5105</changeReasonCode> <changeReasonDescription>No notification trigger found: [triggerDocId :1236]</changeReasonDescription> <changeAction>disable</changeAction> <triggerStateBefore></triggerStateBefore> <triggerStateAfter></triggerStateAfter> <changeDateTime>2011-06-29T07:04:30</changeDateTime> </triggerStateResult> <triggerStateResult> <triggerDocId>1236</triggerDocId> <triggerReference>1237</triggerReference> <changeReasonCode>5105</changeReasonCode> <changeReasonDescription>No notification trigger found: [triggerDocId :1236]</changeReasonDescription> <changeAction>disable</changeAction> <triggerStateBefore></triggerStateBefore> <triggerStateAfter></triggerStateAfter> <changeDateTime>2011-06-29T07:04:30</changeDateTime> </triggerStateResult> <triggerStateResult> <triggerDocId>1236</triggerDocId> <triggerReference>1111</triggerReference> <changeReasonCode>5105</changeReasonCode> <changeReasonDescription>No notification trigger found: [triggerDocId :1236]</changeReasonDescription> <changeAction>disable</changeAction> <triggerStateBefore></triggerStateBefore> <triggerStateAfter></triggerStateAfter> <changeDateTime>2011-06-29T07:04:30</changeDateTime> </triggerStateResult> <triggerStateResult> <triggerDocId>1236</triggerDocId> <triggerReference>1222</triggerReference> <changeReasonCode>5105</changeReasonCode> <changeReasonDescription>No notification trigger found: [triggerDocId :1236]</changeReasonDescription> <changeAction>disable</changeAction> <triggerStateBefore></triggerStateBefore> <triggerStateAfter></triggerStateAfter> <changeDateTime>2011-06-29T07:04:30</changeDateTime> </triggerStateResult> <triggerStateResult> <triggerDocId>1236</triggerDocId> <triggerReference>1333</triggerReference> <changeReasonCode>5105</changeReasonCode> <changeReasonDescription>No notification trigger found: [triggerDocId :1236]</changeReasonDescription> <changeAction>disable</changeAction> <triggerStateBefore></triggerStateBefore> <triggerStateAfter></triggerStateAfter> <changeDateTime>2011-06-29T07:04:30</changeDateTime> </triggerStateResult> <triggerStateResult> <triggerDocId>1236</triggerDocId> <triggerReference>1777</triggerReference> <changeReasonCode>5105</changeReasonCode> <changeReasonDescription>No notification trigger found: [triggerDocId :1236]</changeReasonDescription> <changeAction>disable</changeAction> <triggerStateBefore></triggerStateBefore> <triggerStateAfter></triggerStateAfter> <changeDateTime>2011-06-29T07:04:30</changeDateTime> </triggerStateResult> <triggerStateResult> <triggerDocId>null</triggerDocId> <triggerReference>1212</triggerReference> <changeReasonCode>5105</changeReasonCode> <changeReasonDescription>No notification trigger found: [triggerDocId :null]</changeReasonDescription> <changeAction>disable</changeAction> <triggerStateBefore></triggerStateBefore> <triggerStateAfter></triggerStateAfter> <changeDateTime>2011-06-29T07:04:30</changeDateTime> </triggerStateResult> <triggerStateResult> <triggerDocId>null</triggerDocId> <triggerReference>1313</triggerReference> <changeReasonCode>5105</changeReasonCode> <changeReasonDescription>No notification trigger found: [triggerDocId :null]</changeReasonDescription> <changeAction>disable</changeAction> <triggerStateBefore></triggerStateBefore> <triggerStateAfter></triggerStateAfter> <changeDateTime>2011-06-29T07:04:30</changeDateTime> </triggerStateResult></triggerStateResults></oas:changeNotificationTriggerStatusResult>

but i m getting this error :

[Fatal Error] :1:4730: The end-tag for element type "oas:changeNotificationTriggerStatus" must end with a '>' delimiter.
org.xml.sax.SAXParseException: The end-tag for element type "oas:changeNotificationTriggerStatus" must end with a '>' delimiter.

pls suggest..


View Tutorial          By: Madhu at 2011-06-29 09:47:51
57. View Comment

Very nice tutorial.It helped me a lot cos i am a beginner for these sort of conversions and java.But it would be better to update some of the errors those are posted by users in this.
Anyways just wanted to say thanks...


View Tutorial          By: Fara at 2011-07-01 10:53:44
58. View Comment

very helpful.

View Tutorial          By: arjun at 2011-07-19 03:19:44
59. View Comment

hello,thanx its really great

View Tutorial          By: sadhana at 2011-08-05 09:35:00
60. View Comment

Thank you for this. I am a beg and this is making sense. I need to parse an .xml document for files and their folder location and copy to a set directory. How would I be able to parse a document define what to look for, and take those values to copy?

Thanks


View Tutorial          By: mac at 2011-08-23 13:47:15
61. View Comment

Very helpful stuff. Might I just add that you didn't declare the variable "dom" on your first source code?

But all in all,fantastic tutorials.


View Tutorial          By: Donovan Aces at 2011-09-12 06:08:20
62. View Comment

A wonderful tutorial to learn XML Processing with Java. Thanks a ton :)

View Tutorial          By: Madhan at 2011-09-13 19:37:08
63. View Comment

to Donovan Aces #61, thank you, I am new to java & trying to figure this out for an hour now.

View Tutorial          By: Joe at 2011-09-14 22:40:19
64. View Comment

i have a question..i need to parse an xml file with 5 sub-elements:
<one>
<two>
<three>
<four>
<five>String</five>
</four>
</three>
</two>
</one>

I used the nodelist->element technique (similar to DomParserExample.java) but it seems that it only works until the third subelement (<three>). Is this technique applicable to multiple subelements or is there another way to parse this? Thanks.


View Tutorial          By: meltd0wn at 2011-09-30 08:36:51
65. View Comment

Realy good one

View Tutorial          By: Sabir at 2011-10-25 12:08:43
66. View Comment

Really very nice and step by step explanation help for easy understanding.Thank You

View Tutorial          By: sabarish at 2011-11-08 06:47:49
67. View Comment

where do i download the DOM and SAX jar?

View Tutorial          By: David at 2011-11-11 03:04:11
68. View Comment

nice one ...

View Tutorial          By: vamsi at 2011-11-11 06:41:25
69. View Comment

Nice basics. Very helpful

View Tutorial          By: Gorav at 2011-11-11 12:46:28
70. View Comment

The SAX Parser code has a problem for files of greater than 2048 bytes. The SAX Parser only reads in 2048 bytes at a time which could lead to an error if the 2048-byte sections split your element's data. The solution I found is to create your tempVal String (or StringBuffer in my case) in your startElement method call and then add to it in the characters method call.

public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
//reset
tempVal = new StringBuffer();
if(qName.equalsIgnoreCase("Employee")) {
//create a new instance of employee
tempEmp = new Employee();
tempEmp.setType(attributes.getValue("type"));
}
}


public void characters(char[] ch, int start, int length) throws SAXException {
tempVal.append(new String(ch, start, length));
}


View Tutorial          By: Mark Nelson at 2011-11-14 20:16:41
71. View Comment

Many thanks for this tutorial - it has saved me some time.

View Tutorial          By: Ehsan at 2011-11-20 23:12:21
72. View Comment

clearly explained the pgm logic....
thnx.......


View Tutorial          By: Akshaya at 2011-11-24 04:12:36
73. View Comment

the DomParserExample.java shows MAlformedURLException.
For this purpose,we got to add this line:
File f=new File("xyz.xml");

and then add dom = db.parse(f);


View Tutorial          By: dipesh at 2011-12-09 09:53:46
74. View Comment

Thanks for the clear explanation..
Really helpful..

1 question..how do we gather all the children of a particular element as a list of Elements? I tried using the getChildNodes() function but it gets a NodeList of Nodes which is not what I want.
Any help will be appreciated.
Thanks..


View Tutorial          By: Swj at 2011-12-30 05:55:26
75. View Comment

Hi all

I am using getAttribute but its not returning the answer i expect. I have an XML string: <TestDoc><templateName>myReportName</templateName></TestDoc>

I have converted this into a DOM doc called inputDoc and now i want to get the value of the attribute templateName.

i have:

Element root = inputDoc.getDocumentElement();
String Template = root.getAttribute("templateName");

and it returns null as Template. Any ideas?

Thanks very much.


View Tutorial          By: Suvarna at 2012-01-12 06:56:55
76. View Comment

Excellent tutorial thank you very much.

For other people who are new to this i only needed to do two things to make it work:

1. Initialize a Document object "dom". To do this you need to import the following: import org.w3c.dom.Document;

2. Create a class "Employee" with the relevant variable and a constructor to set these when new objects are created from the method: Employee e = new Employee(name,id,age,type);

Thanks again for a great tutorial.


View Tutorial          By: Edd at 2012-01-15 10:49:00
77. View Comment

Very helpful.

View Tutorial          By: Krishna at 2012-06-14 10:25:00
78. View Comment

where i can find jar files?
please tell me to which jar file set classpath?


View Tutorial          By: chandu at 2012-06-17 14:14:28
79. View Comment

Very helpful!!

View Tutorial          By: mahesh at 2012-07-12 06:24:50
80. View Comment

Awesome tutorial

View Tutorial          By: Anonymous at 2012-12-13 06:50:36
81. View Comment

Thanks alot that was quite helpful!

View Tutorial          By: Doaa at 2013-01-09 09:37:35
82. View Comment

Hi mate,
When I compile the DomParserExample.java I ended up with the following errors.
DomParserExample.java:183: cannot find symbol
symbol : class Employee
location: class DomParserExample
private Employee getEmployee(Element empEl) {
^
DomParserExample.java:153: cannot find symbol
symbol : class Employee
location: class DomParserExample
Employee e = getEmployee(el);
^
DomParserExample.java:205: cannot find symbol
symbol : class Employee
location: class DomParserExample
Employee e = new Employee(name,id,age,type);
^
DomParserExample.java:205: cannot find symbol
symbol : class Employee
location: class DomParserExample
Employee e = new Employee(name,id,age,type);
^
4 errors

Could you please help me to rectify that.


View Tutorial          By: Suresh Kumar D at 2013-06-25 07:06:19
83. View Comment

This is the helpful Site for beginner....!!!!!!!!!!!!!

View Tutorial          By: Anup at 2013-07-26 13:40:49
84. View Comment

Where should I put the xml file ??????????

View Tutorial          By: Marya at 2014-03-21 16:01:13
85. View Comment

Great tutorial

View Tutorial          By: Stephen at 2014-07-21 12:08:32
86. View Comment

how to read any xml file or i want to a universal code for read or write xml file in java

View Tutorial          By: shankar lal at 2014-09-29 12:40:20
87. View Comment

You may add STAX parser example also to complete this. As with Java 6, STAX parser is latest trend.

View Tutorial          By: Satyam Jaiswal at 2014-11-25 05:48:59
88. View Comment

really helpfull :) thanks

View Tutorial          By: Jagan at 2014-12-09 10:16:56
89. View Comment

Hi All,

Can any one please let me know how to write the result that has been produced by the DomParseExample.java in the MongoDB Data base ?


View Tutorial          By: Deepak at 2015-03-19 15:24:40
90. View Comment

Nice tutorial, I got how it's done, but the difference from one method (DOM) to the other (SAX) is meaningful enough to be explained. For those who are still asking what the difference is, this is a great post to read:
http://stackoverflow.com/questions/6828703/what-is-the-difference-between-sax-and-dom


View Tutorial          By: FriendlyNoob at 2015-07-20 17:27:08

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by totheriver.com
XML and Java - Parsing XML using Java Tutorial

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
Stack example in Java - push(), pop(), empty(), search()
Read from a COM port using Java program
FileReader and FileWriter example program in Java
XML and Java - Parsing XML using Java Tutorial
Using StringTokenizer in Java
How to use Iterator in Java
Abstract classes in Java
How to use ArrayList in Java
The Basic Structure of a Simple Java program
Recursion in java
Method Overriding in Java
append() in Java
Method Overloading (function overloading) in Java
Student marks calculation program in Java
Most Emailed Articles (in Java)
Tomcat and httpd configured in port 8080 and 80
Vector in Java - Sample Program
Get user input in Java
FilenameFilter - sample program in Java
How to Send SMS using Java Program (full code sample included)
Update contents of a file within a jar file
Count number of vowels, consonants and digits in a String in Java
Java program using Method Overriding
Using StringTokenizer in Java
How to use ArrayList in Java
MultiLevel Inheritance sample in Java
What is a deadlock and how to avoid it in Java
how to use boolean data type in Java
Extract characters in Java
Supports mobile tournament games