How to parse xml from android project resources
I have an XML file (config.xml) in the res / xml folder and I need to parse this XML. I use SAXParser for this. I try like this:
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
//handler definition...
};
Uri configUri = Uri.parse("android.resource://myPackageName/" + R.xml.config);
saxParser.parse(configXML.toString(), handler);
But that doesn't work ...
The parse method has the following parameters:
uri Location of parsed content.
dh Use SAXDefaultHandler.
Should I be using a URI or Uri? What is the difference?
source to share
I have an XML file (config.xml) in res / xml folder and I need to parse this XML
Call getResources().getXml(R.xml.config)
. You will be given XmlResourceParser
which API will follow XmlPullParser
. As shown in the XmlPullParser
JavaDocs , you complete the code like this:
XmlResourceParser xpp=getResources().getXml(R.xml.config);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
// do something
} else if (eventType == XmlPullParser.START_TAG) {
// do something
} else if (eventType == XmlPullParser.END_TAG) {
// do something
} else if (eventType == XmlPullParser.TEXT) {
// do something
}
eventType = xpp.next();
}
I use SAXParser for this
Even if you can get this to work, it will be ~ 10x slower than using XmlResourceParser
.
source to share