views:

41

answers:

1
+1  Q: 

Xml Parsing Error

Hello All!

I am getting this error while trying to Parse the Xml response from the Web Service by SAX Parser in Android.

ERROR in LogCat :- " Response =====> org.xml.sax.InputSource@43b8e230 " 

I got to know that I need to convert the response in String may be by toString() Method, but the problem is I don't know how to do that as I had tried all the possible ways I knew for conversion but nothing happened.

In InputSource I am passing the url:-

URL url = new URL("http://www.google.com/ig/api?weather=Ahmedabad");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xmlr = sp.getXMLReader();
DemoHandler myDemoHandler = new DemoHandler();
xmlr.setContentHandler(myDemoHandler);
xmlr.parse(new InputSource(url.openStream()));
Log.e(TAG, "Condition"); 
System.out.println("Response ====> " + new InputSource(url.openStream().toString()));
ParsedDemoData parsedDemoData = myDemoHandler.getParsedData();

Everything is fine but the response I am getting needs to be converted into String which I don't know how to do.

Can anyone please help in this.

Thanks, david

+1  A: 

To parse an InputStream you don't have to convert it into a string you can directly read its elements and attributes using Parsers available on Android. You can refer the following links to do the same

http://www.ibm.com/developerworks/opensource/library/x-android/index.html

http://www.anddev.org/parsing_xml_from_the_net_-_using_the_saxparser-t353.html

How ever if you are looking for a code that converts Input Stream to string something like this will work

 public String convertStreamToString(InputStream is) throws IOException {
            /*
             * To convert the InputStream to String we use the BufferedReader.readLine()
             * method. We iterate until the BufferedReader return null which means
             * there's no more data to read. Each line will appended to a StringBuilder
             * and returned as String.
             */
            if (is != null) {
                StringBuilder sb = new StringBuilder();
                String line;

                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    while ((line = reader.readLine()) != null) {
                        sb.append(line).append("\n");
                    }
                } finally {
                    is.close();
                }
                return sb.toString();
            } else {        
                return "";
            }
        }

And this should print the stream for you

System.out.println("Response ====> " + convertStreamToString(url.openStream()));
Rahul
Thank you So Very Much Mr.Rahul for your Support, reffering to your answer I finally could do it. Thanks once again for such a stress releiving answer.
david