Sunday, June 12, 2011

How to Parse XML using Java


Step1:- 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 staff.xml file with content as below



<?xml version="1.0"?>
<company>
 <staff>
  <firstname>Amit</firstname>
  <lastname>Mangal</lastname>
  <nickname>Tiger</nickname>
  <salary>100000</salary>
 </staff>
 <staff>
  <firstname>Lalit</firstname>
  <lastname>Aggarwal</lastname>
  <nickname>Lalit</nickname>
  <salary>200000</salary>
 </staff>
</company>

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

Root element :company
-----------------------
First Name : Amit
Last Name : Mangal
Nick Name : Tiger
Salary : 100000
First Name : Lalit
Last Name : Aggarwal
Nick Name : Lalit
Salary : 200000

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.

No comments: