Tuesday, October 20, 2009

Java : Simple XML Parser

/* SimpleXmlParser.java */

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class SimpleXmlParser
{
public static void main(String[] args)
{
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

Document dom = null;

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

dom = db.parse("xmlFile.xml");

//get the root elememt
Element docEle = dom.getDocumentElement();

//get a nodelist of slot elements
NodeList nl = docEle.getElementsByTagName("Employee");

if(nl != null && nl.getLength() > 0)
{
for(int i = 0 ; i < nl.getLength();i++)
{
System.out.println("--Employee--");

Element el = (Element)nl.item(i);

System.out.println("Name : "+getTextValue(el,"Name"));
System.out.println("Designation : "+getTextValue(el,"Designation"));
System.out.println("Department : "+getTextValue(el,"Department"));
}
}
}
catch(Exception ex)
{
System.out.println("Exception : "+ex);
}
}

public static 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;
}
}


/* xmlFile.xml */

<AllEmployee>
<Employee>
<Name>Ram</Name>
<Designation>Programmer</Designation>
<Department>Development</Department>
</Employee>
<Employee>
<Name>Shyam</Name>
<Designation>TL</Designation>
<Department>Finanace</Department>
</Employee>
<Employee>
<Name>Geeta</Name>
<Designation>Manager</Designation>
<Department>HR</Department>
</Employee>
</AllEmployee>

Output

--Employee--
Name : Ram
Designation : Programmer
Department : Development
--Employee--
Name : Shyam
Designation : TL
Department : Finanace
--Employee--
Name : Geeta
Designation : Manager
Department : HR