问题
I have a xml file in the location res/xml/data.xml
I need to parse that xml file
XmlResourceParser xrp=context.getResources().getXml(R.xml.data);
I used this code to get that file. It returns as XmlResourceParser
Also tried with xmlpullparser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
I am not getting clear idea between these two parser. My question is how to parse a xml file in the resource folder using xmlpullparser
?
回答1:
XmlResourceParser
is an interface
which extends XmlPullParser
.
getXml
wil return the XmlResourceParser
object. You can read the parser text similar to how we parse the input stream or a string using XMLPullParser
Here is a sample code to parse from resource xml
try {
XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.data);
int eventType = xmlResourceParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if (eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag " + xmlResourceParser.getName());
} else if (eventType == XmlPullParser.END_TAG) {
System.out.println("End tag " + xmlResourceParser.getName());
} else if (eventType == XmlPullParser.TEXT) {
System.out.println("Text " + xmlResourceParser.getText());
}
eventType = xmlResourceParser.next();
}
System.out.println("End document");
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
来源:https://stackoverflow.com/questions/23175773/android-parse-using-xmlpullparser