java - 在 Android 中解析 XML 流

标签 java android xml inputstream

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

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

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

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

found 必须等于 20。

最佳答案

使用:

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

关于java - 在 Android 中解析 XML 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9360425/

相关文章:

java - Appium:如何在appium中搜索后点击第一个链接

java - 使用 new 关键字从同一包内的类外部调用它时在框架内获取空文本区域

检查外部存储状态时 Android logcat 错误 "getExternalStorageState/mnt/sdcard"

android sqlite 从列表菜单中删除

java - 如何为弹出菜单项插入图标

javascript - XHTML/JavaScript 动态内容未格式化

java - 在 XStream 中将日期字段格式化为字符串

javascript - Nashorn:在命名空间内调用函数

android - 检查 Playstore 中的内部测试人员是否安装了该应用程序

javascript - 使用 javascript 在另一个 URL 上运行 GET、检索返回的 xml 并查找特定节点的示例?