I need help :D. I am using web service that returns similar xml file to the one below:
<books>
<item_1>
<name></name>
<type></type>
</item_1>
<item_2>
<name></name>
<type></type>
</item_2>
<item_3>
<name></name>
<type></type>
</item_3>
...
...</books>
The problem is that I don’t know how to parse it in Android. Everything would be fine if the child elements of the ‘books’ tag would have the same name (item instead of: item_1, item_2, item_3…) Then I could easily use SAX parser.
Do you know how I could pare this kind of document in Android?
Thanks,
marqs
EDITED:
My problem is that the child elements of <<>books> tag ale numbered (item1,item2,item3 and so on) so I cannot identify them. That would not be a problem if the ‘books’ tag would have only ‘item’ child – so then I could use SAX parser and fetch ‘item’ list
The problem that you’ve described doesn’t sound all that hard: If you can safely assume that every child of the books element is an “item”, then you can invoke your “item handler” for each child.
Here’s pseudocode that (I think) would work, assuming that <books> is always and only the top-level element of the document:
Even as pseudocode, that’s over-simplistic and ugly. An alternative approach, but which may be overblown for your needs, is to decompose your application into multiple
ContentHandlerclasses, passing off responsibility as you reach the beginning or ending of certain elements.For example: Let’s assume that an instance of BookHandler is passed in to the parser.parse() call, to handle the top-level elements. Then:
This scheme offers more flexibility, and more possibilities for reuse. For example, potentially the “books” element could now be a child of some other element, say “departments”, without requiring much if any changes to these classes.
The pseudo-code isn’t perfect by any means. (For one thing, I’d want to think some more about where the handlers are switched off — in the parent class, or in the child. For another thing, I may have gone overboard in saving references to both parents and children in these classes.) But I hope it gives you ideas that you can start working with.