Thursday, July 26, 2007

Code Snippets:XML Parsing using SAX

This code snippet shows parsing of an XML document using SAX parser.

import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReadXML {

public static void main(String argv[]) {
try {

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("employee.xml"));

doc.getDocumentElement().normalize();
System.out.println("Root element of the document is "
+ doc.getDocumentElement().getNodeName());

NodeList listOfEmployees = doc.getElementsByTagName("employee");
int totalEmployees = listOfEmployees.getLength();
System.out.println("Total no of employees : " + totalEmployees);

for (int i = 0; i < listOfEmployees.getLength(); i++)
{

Node firstEmpNode = listOfEmployees.item(i);
if (firstEmpNode.getNodeType() == Node.ELEMENT_NODE)
{

Element firstEmpElement = (Element) firstEmpNode;

// NodeList of first name
NodeList firstNameList = firstEmpElement
.getElementsByTagName("first");
Element firstNameElement = (Element) firstNameList.item(0);

NodeList txtFirstNameList = firstNameElement
.getChildNodes();
System.out.println("First Name : "
+ ((Node) txtFirstNameList.item(0)).getNodeValue()
.trim());

// NodeList of last name
NodeList lastNameList = firstEmpElement
.getElementsByTagName("last");
Element lastNameElement = (Element) lastNameList.item(0);

NodeList txtLastNameList = lastNameElement.getChildNodes();
System.out.println("Last Name : "
+ ((Node) txtLastNameList.item(0)).getNodeValue()
.trim());

// NodeList of id
NodeList idList = firstEmpElement
.getElementsByTagName("id");
Element idElement = (Element) idList.item(0);

NodeList txtIdList = idElement.getChildNodes();
System.out.println("Id : "
+ ((Node) txtIdList.item(0)).getNodeValue().trim());

}

}

} catch (SAXParseException saxParseException) {
saxParseException.printStackTrace();
} catch (SAXException saxException) {
saxException.printStackTrace();

} catch (Throwable throwable) {
throwable.printStackTrace();
}

}// end of main

}



Input XML file, 'employee.xml':

<employees><employee>
<first>Tom</first>
<last>Cruise</last>
<id>MI24</id>
</employee>
<employee>
<first>Clint</first>
<last>Eastwood</last>
<id>XY01</id>
</employee>
<employee>
<first>Sean</first>
<last>Connery</last>
<id>JB07</id>
</employee>
</employees>



And here is the output of executing this code:

Root element of the document is employees
Total no of employees : 3
First Name : Tom
Last Name : Cruise
Id : MI24
First Name : Clint
Last Name : Eastwood
Id : XY01
First Name : Sean
Last Name : Connery
Id : JB07

0 comments:

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2012