下面是显示所有xml的代码。我不想显示所有xml内容,但只想检查id = 2是否显示描述。请帮我修改代码。
private String getEventsFromAnXML(Activity activity)throws XmlPullParserException, IOException
{
StringBuffer stringBuffer = new StringBuffer();
Resources res = activity.getResources();
XmlResourceParser xrp = res.getXml(R.xml.books.xml);
xrp.next();
int eventType = xrp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser.START_DOCUMENT)
{
stringBuffer.append(" ");
}
if(eventType == XmlPullParser.START_TAG)
{
stringBuffer.append("First Tag " + xrp.getName());
}
else if(eventType == XmlPullParser.TEXT)
{
stringBuffer.append("Second Tag "+xrp.getText());
}
else if(eventType == XmlPullParser.END_TAG)
{
stringBuffer.append("Third Tag "+xrp.getName());
}
eventType = xrp.next();
}
stringBuffer.append("\n--- End XML ---");
return stringBuffer.toString();
}
我的xml文件
<?xml version="1.0" encoding="utf-8" ?>
<Books>
<Number id ="1">
<Description>This is science book.
</Description>
</Number>
<Number id = "2">
<Description>This is about cooking.
</Description>
</Number>
</Books>
答案 0 :(得分:0)
Heer是代码.....
private String getEventsFromAnXML()throws IOException,XmlPullParserException
{
String attVal = null;
String desc = null;
String startTag = null;
Resources res = this.getResources();
XmlResourceParser xrp = res.getXml(R.xml.book);
xrp.next();
int eventType = xrp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser.START_TAG){
startTag = xrp.getName();
if(startTag.equals("Number")){
attVal = xrp.getAttributeValue(0);
}
}
else if(eventType == XmlPullParser.TEXT){
if(startTag.equals("Description") && attVal.equals("2"))
desc = xrp.getText();
}
else if(eventType == XmlPullParser.END_TAG)
{
}
eventType = xrp.next();
}
return desc;
}