在Android中解析XML流

时间:2012-02-20 11:32:21

标签: java android xml inputstream

我不知道为什么,但Log.i(TAG,“发现:”+发现);为我的XML中的“found”元素返回null,我在流中获取。我已经调试了,似乎我读取了我的XML根元素,但是根元素的元素却没有。 urlString也是正确的。解析文档时没有任何错误和异常。但是在这一行

NodeList nl = docEle.getElementsByTagName("found");
        found = nl.item(0).getNodeValue();

发现是null。这是方法的完整代码:

protected Void doInBackground(String... urls) {

        String urlString = urls[0];
        URL documentUrl = null;
        InputStream stream = null;
        URLConnection conn = null;
        DocumentBuilder builder = null;
        Document document = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            builder = factory.newDocumentBuilder();

            documentUrl = new URL(urlString);
            conn = documentUrl.openConnection();
            stream = conn.getInputStream();
            document = builder.parse(stream);
        } 
        catch (IOException e) {
            Error = e.getMessage();
            Log.i(TAG, "Exception!", e);
        } 
        catch (SAXException e) {
            Error = e.getMessage();
            Log.i(TAG, "Exception!", e);
        }
        catch (ParserConfigurationException e) {
            Error = e.getMessage();
            Log.i(TAG, "Exception!", e);
        }
        finally 
        {
            if (stream != null)
            {
                try {
                    stream.close();
                } catch (IOException e) {
                    Error = e.getMessage();
                    Log.i(TAG, "Exception!", e);
                }
            }
        }

        /*NodeList nodes = document.getElementsByTagName("found");
        for (int i = 0; i < nodes.getLength(); i++) {
            found = nodes.item(i).getNodeValue();
            //System.out.println(found);
            Log.i(TAG, "found: "+found);
        }*/

        //get the root element
        Element docEle = document.getDocumentElement();
        NodeList nl = docEle.getElementsByTagName("found");
        found = nl.item(0).getNodeValue();
        Log.i(TAG, "found: "+found);

        return null;
    }

这是我的带有XML的urlString:http://basa.med-info.ru/xse/index.php?query=%E3%F0%E8%EF%EF&nres=20

发现必须等于20.

1 个答案:

答案 0 :(得分:2)

使用:

found = nl.item(0).getFirstChild().getNodeValue();