XML SAX Parser in Java

The same 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 SAX parsing

private List<Person> list;
private Person p;
private String tmpValue;

public List<Person> parse(InputStream is) {
	list = new ArrayList<Person>();
	SAXParserFactory spf = SAXParserFactory.newInstance();
	SAXParser sp = spf.newSAXParser();
	sp.parse(is, this);
	
	return list;
}

public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
	if (qName.equalsIgnoreCase("person")) {
		tmpValue = "";
		p = new Person();
	}
}

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

public void endElement(String uri, String localName, String qName) throws SAXException {
	if (qName.equalsIgnoreCase("name")) {
		p.setName(tmpValue);
	}
	if (qName.equalsIgnoreCase("age")) {
		p.setAge(Integer.parseInt(tmpValue));
	}
	if (qName.equalsIgnoreCase("sex")) {
		p.setSex(tmpValue);
	}
	if (qName.equalsIgnoreCase("location")) {
		p.setLocation(tmpValue);
	}

	if (qName.equalsIgnoreCase("person")) {
		list.add(p);
	}
}

http://www.java-samples.com/showtutorial.php?tutorialid=152

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: