How to parse different XML files using SAX on Android?

泪湿孤枕 提交于 2019-12-08 07:31:07

问题


I have the following scenario.

I send a XML file to a server as a request and get a XML file as response and all that as a background thread on Android.

The XML request is serialized using various values. The XML response is then read by SAX and put into a list. The whole request/response process happens in a background thread using the AsyncTask class.

The problem is that I have different types of responses and I have no idea what approach to take to parse the response based on the request sent.

How do I tell Android to use parser A based on request A and parser B based on request B?

EDIT: With different types of responses I mean the XML file looks different. It has different tags and different attributes.


回答1:


Here are the options as I see them:

  1. You can base the parsing capability based on the request (which should have some kind of context). If you know the request is Type A, then you know the response MUST use parser A.
  2. You can have generic parser for all types, and branch what happens in the parser based on the first known tag or attribute that dictates what should be done.
  3. Parse first, analyze after. Take all the response elements, and build object or object graphs out of them. Pass those around, mutate them if need be for your application (don't try to edit xml - you're parsing it after all, and you want that to finish ASAP).

Good luck!




回答2:


the are all message response object, specify an attribute to indicate and object type in the xml response

<response>
<error/>
<data type="A">
</data>
</response>

<response>
<error/>
<data type="B">
</data>
</response>


来源:https://stackoverflow.com/questions/3583876/how-to-parse-different-xml-files-using-sax-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!