tags:

views:

89

answers:

4

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?

+1  A: 

Depends 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.

StaxMan
I am doiing a journey planner app and I need to parse jurneys from the xml I receive from server.
fhucho
JAXB is not an option in Android, currently.
Mayra
I will use DOM for now. When everything's working and it will be slow, I'll rewrite the code to SAX or pull parser.
fhucho
Too bad if JAXB can't be made to work -- I know there used to be issues with API blacklisting. As to pull parser; last thing to suggest is having a look at StaxMate (http://staxmate.codehaus.org), which IMO makes them much nicer to use.
StaxMan
+1  A: 

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.

Noel
+1  A: 

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.

Mayra
A: 

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/

Adrian Petrescu