How to parse a local XML file in Android?
I want to retrieve data from an xml file in android app. Below is the code I am working with. I think the if statements I am using are not working well ( they are not picking the description to display). I want to display the text(description) if the id value is for example 2. Please review the code and help me correct it.Thanks.
<?xml version="1.0" encoding="utf-8" ?>
<Books>
<Number id ="1">
<Description>This text is for id whose value is equal to 1. </Description>
</Number>
<Number id = "2">
<Description>This text is for id whose value is equal to 2. </Description>
</Number>
</Books>
String stringXmlContent;
try {
stringXmlContent = getEventsFromAnXML(this);
tv.setText(stringXmlContent);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
button1.setOnClickListener(this);
private String getEventsFromAnXML(Activity activity)throws XmlPullParserException, IOException
{
StringBuffer stringBuffer = new StringBuffer();
String attVal = null;
String desc;
Resources res = activity.getResources();
XmlResourceParser xrp = res.getXml(R.xml.myxml);
try {
xrp.next();
开发者_StackOverflow中文版 int eventType = xrp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser.START_DOCUMENT)
{
stringBuffer.append(" ");
}
if(eventType == XmlPullParser.START_TAG)
{
if(xrp.getName().equals("Number")){
attVal = xrp.getAttributeValue(0);
}
}
else if(eventType == XmlPullParser.TEXT)
{
if(xrp.getName().equals("Description") && attVal.equals("2")){
stringBuffer.append(" " + xrp.getText());
}
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stringBuffer.toString();
}
精彩评论