XML Dom Parser in Java

A simple XML

<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person>
		<name>debraj</name>
		<age unit="year">23</age>
		<sex>male</sex>
		<location>india</location>
	</person>
	<person>
		<name>ritu</name>
		<age unit="year">33</age>
		<sex>female</sex>
		<location>india</location>
	</person>
</persons>

The parsing

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser;

parser = factory.newDocumentBuilder();
Document doc = parser.parse(new InputSource(is));

NodeList persons = doc.getElementsByTagName("persons");
NodeList personList = persons.item(0).getChildNodes();

for (int i = 0; i < personList.getLength(); i++) {
	Node person = personList.item(i);

	if (person.getNodeType() == Node.ELEMENT_NODE) {
		NodeList personDetail = person.getChildNodes();
		Person p = new Person();
		for (int j = 0; j < personDetail.getLength(); j++) {
			Node n = personDetail.item(j);

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

				if (n.getNodeName() == "name") {
					p.setName(n.getTextContent());
				}
				if (n.getNodeName() == "age") {
					p.setAge(Integer.parseInt(n.getTextContent()));
				}
				if (n.getNodeName() == "sex") {
					p.setSex(n.getTextContent());
				}
				if (n.getNodeName() == "location") {
					p.setLocation(n.getTextContent());
				}
			}
		}
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: