XML StAX 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>

and the StAX parsing

XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(is);

while (streamReader.hasNext()) {
	streamReader.next();
	if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT) {
		if (streamReader.getLocalName() == "person") {
			Person p = new Person();
			while (streamReader.hasNext()) {
				streamReader.next();
				if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT) {
					if (streamReader.getLocalName() == "name") {
						p.setName(streamReader.getElementText());
					}
					if (streamReader.getLocalName() == "age") {
						p.setAge(Integer.parseInt(streamReader.getElementText()));
					}
					if (streamReader.getLocalName() == "sex") {
						p.setSex(streamReader.getElementText());
					}
					if (streamReader.getLocalName() == "location") {
						p.setLocation(streamReader.getElementText());
						break;
					}
				}
			}
		}
	}
}

http://tutorials.jenkov.com/java-xml/stax-xmlstreamreader.html
http://javaboutique.internet.com/tutorials/stax/index3.html

Advertisements