Xml解析错误

时间:2010-09-18 05:43:47

标签: android xml parsing

尝试通过Android中的SAX Parser从Web服务解析Xml响应时出现此错误。

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

我知道我需要转换String中的响应可能是通过toString()方法,但问题是我不知道怎么做,因为我已经尝试了所有可能的方法,我知道转换但什么也没发生。

在InputSource中,我传递了网址: -

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();

一切都很好,但我得到的反应需要转换成字符串,我不知道该怎么做。

任何人都可以帮忙。

谢谢, 大卫

1 个答案:

答案 0 :(得分:1)

要解析InputStream,您不必将其转换为字符串,您可以使用Android上提供的解析器直接读取其元素和属性。您可以参考以下链接来执行相同的操作

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

如果您正在寻找将输入流转换为类似字符串的代码,那将会起作用

 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 "";
            }
        }

这应该为你打印流

System.out.println("Response ====> " + convertStreamToString(url.openStream()));