Volley library for Android parse xml response?

前端 未结 4 635
一生所求
一生所求 2020-12-06 11:08

I am using volley library and getting response in XML.I want to know how we can parse response using /volley library.Thank you.

4条回答
  •  -上瘾入骨i
    2020-12-06 12:03

    Here is my solution. As Sir Alif said above, volley can provide you with raw string of XML data, received from the server. So, all you need to do is to parse this String accordinly to your app logic. So, for parsing the String I used SAX parser. I'm not going to describe here how to use SAX parser cause you can find tons of tutorials by yourself, I'll just describe the key point. The piece of code below shows the moment when you create instances of SAXParserFactory, SAXParser, XMLReader etc., also here you create an instance of InputSource, and this is the key point. Commonly, you open a connection, using certain url address, and then SAX parser parses received data for you. But, as far as we are trying to use Volley library, we will give InputSource not the InputStream, but a StringReader (full information about input source and its public constructors you can find here). It will look like this:

    public void makeList(String s){   
       SAXParserFactory factory = SAXParserFactory.newInstance();
       SAXParser sp = factory.newSAXParser();
       XMLReader xmlReader = sp.getXMLReader();
       SaxHandler handler = new SaxHandler();
       xmlReader.setContentHandler(handler);                               
       InputSource is = new InputSource(new StringReader(s));
       is.setEncoding("UTF-8");
       xmlReader.parse(is); 
    }
    

    So, in the Activity, where you get the StringRequest from Volley, in onRespone() method you can pass that response to the makeList(String s) method (or to whatever you called the method with the same functionality), which will parse you that response. Hope this helps! If you have some questions please ask in comments.

提交回复
热议问题