In my Android app I need to extract data from a xml file (the file will have less than 2000 lines). I have no experience with XML parsing, so I don't know what the best approach is. DOM parser is perhaps not a good option, because I am on a mobile device. On the other hand with SAX I would probably end with more complicated code. What would you recommend?
views:
89answers:
4Depends on exactly what you want to extract, but for small enough documents I don't think DOM is too bad, and it comes bundled with JDK (I think on android too). For ultimate convenience I would use JAXB, to bind to Java beans; it uses SAX parser by default and is more efficient than using DOM trees (as well as easier to use).
Otherwise I would look into pull parsers; android ships with xpp which is ok, but Woodstox is my favorite.
If you are familiar with XPath, that is an option. I don't know if it would give you better performance compared to a parser.
For parsers, I would recommend going with the SAX parser. It is usually pretty easy to work with. If you extend the DefaultHandler, there are a bunch of functions which you can override and leverage for your purposes. Some include:
void startElement()
- called for each start tag, function call also passes in attributes as an argument
void characters()
- called for the content within a tag
void endElement()
- called for each end/closing tag
See the API reference for additional details.
There are 3 options for parsing XML on Android, by default, DOM, SAX and PullParser. There is no right answer as to which is best to use, it depends on your app. You can find details on all them here though.
If its something thats going to happen a lot, probably worth it to use a SAX or pull parser to be more efficient.
As mentioned on another question similar to this one, there's a JAXB-like implementation that has been stripped down and plays well with Android. It's called Simple and you can find it here: http://simple.sourceforge.net/