XML SAX Parser in Java
August 28, 2010 Leave a comment
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