Can anyone point me to a explanation for or explain to me how I can easily parse the XML and get values of a w3c.Document on Android using only Android OS Libs?
I tr
We can also use XPath in Android XML Parsing Things ..
It is useful when you are coming to parse a lot of data in form of an Array.
Check out this Link for XPath Tutorial in parsing XML Content from Android.
Enjoy !!
Here's an article at Developer.com comparing the performance of the DOM, SAX and Pull parsers on Android. It found the DOM parser to be by far the slowest, then the Pull parser and the SAX parser the fastest in their test.
If you're going to be a doing a lot of parsing in your application it may be worth benchmarking the different options to see which works best for you.
I've used the XmlPullParser via XmlResourceParser and found that worked well and was easy to use.
It works through the XML returning events telling you what it's found in there.
If you use it, your code will look something like this:
XmlResourceParser parser = context.getResources().getXml(R.xml.myfile);
try {
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
switch (eventType){
case XmlPullParser.START_TAG:
name = parser.getName().toLowerCase();
if (name.equals(SOME_TAG)) {
for (int i = 0;i < parser.getAttributeCount();i++) {
String attribute = parser.getAttributeName(i).toLowerCase();
if (attribute.equals("myattribute")) {
String value = parser.getAttributeValue(i);
}
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
break;
}
eventType = parser.next();
}
}
catch (XmlPullParserException e) {
throw new RuntimeException("Cannot parse XML");
}
catch (IOException e) {
throw new RuntimeException("Cannot parse XML");
}
finally {
parser.close();
}
If you want to parse XML that's not from a resource file you could create a new XmlPullParser
using the XmlPullParserFactory class and then call the setInput() method.
You should definitively use the SAX APIs provided. Android XML parse API stacks on top of the normal java SAX one so in my opinion I would just use the normal Java SAX API and this way you get the ability to test your code as normal java desktop project.
XML parsing is always slow and using these SAX parsers is as good as it gets (unless you write a custom parser from the scratch). Word of advice: Try to minimize string comparison and try to use hashmaps instead of long chains of if (token.isEqual(CONSTANT_TOKEN));.
Here are a few examples of Java XML parsing: http://java.sun.com/developer/codesamples/xml.html#sax
Android XML API is declarative, the paradigm is a bit different so in case you decide going with that, be prepared to read a few examples to learn its ways.
Finally, maybe 2 months ago I saw a chart benchmarking DOM vs SAX vs Android XML API (I can't quite find the link now). The conclusion was that DOM was by far the slowest and SAX was top but not by a huge margin over Android's XML implementation.