我想从android app中的xml文件中检索数据。以下是我正在使用的代码。我认为我使用的if语句效果不佳(他们没有选择要显示的描述)。我想显示文本(描述),如果id值是例如2.请查看代码并帮我纠正它。谢谢。
<?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();
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();
}