I need to read a XML using XMLPullParser. But when I try to parse it my eventType starts with 0 (i.e., START_DOCUMENT) and immediately skips to 1 (i.e., END_DOCUMENT) thereby skipping all the other tags.
Here's my sample code:
public void parseProperties (InputStream in)
{
try
{
XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser pullParser = pullParserFactory.newPullParser();
pullParser.setInput(in, null);
int eventType = pullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
String name = pullParser.getName();
switch (eventType)
{
case XmlPullParser.START_TAG:
break;
case XmlPullParser.END_TAG:
break;
}
eventType = pullParser.next();
}
}
catch (XmlPullParserException ex)
{
}
catch (IOException ex)
{
}
finally
{
}
}
Can someone please tell me why I'm not able to hit any switch cases?
This always works for me:
public class ParseXML {
private String xmlData;
public ParseXML (String xmlData) {
this.xmlData = xmlData;
}
public boolean process () {
boolean status = true;
boolean inEntry = false;
String textValue = "";
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(this.xmlData));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName = xpp.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagName.equalsIgnoreCase("MyTagStart")) {
inEntry = true;
}
break;
case XmlPullParser.TEXT:
textValue = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (inEntry) {
if (tagName.equalsIgnoreCase("MyTagEnd")) {
inEntry = false;
}
else if (tagName.equalsIgnoreCase("SomeTag")) {
someInfo.setInfo(textValue);
}
}
break;
default:
//
}
eventType = xpp.next();
}
} catch (Exception e) {
status = false;
e.printStackTrace();
}
return true;
}
}
and you just create an instance passing your XML data:
ParseXML parseXML = new ParseXML(contentXML);
parseXML.process();