0

我正在创建一个 android 应用程序来解析 RSS 提要,在过去的几周里它一直运行良好。但最近其中一篇文章有​​一个<enclosure>标签,应用程序停止工作,logcat 指出 DOMParser 抛出了 NullPointerException。
我经历并尝试了我对Java的了解可能做的所有事情。但无济于事。

附带说明一下,如果我手动删除有问题的标签,问题就解决了,应用程序再次正常工作。

这是我正在解析的 xml

<item>
<title>Title</title>
<link>Link</link>
<pubDate>Sun, 27 Jan 2013 05:08:30 +0000</pubDate>
<dc:creator></dc:creator>
<guid isPermaLink="false">guid</guid>
<content:encoded>
Content
</content:encoded>
<enclosure url="" length="22836034" type="audio/mpeg"/>
</item>

我删除了不相关的标签并替换了信息以保护隐私并保持简短

和解析器的一部分:

Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();


            NodeList nl = doc.getElementsByTagName("item");



            int length = nl.getLength();

            for (int i = 0; i < length; i++) {
                Node currentNode = nl.item(i);
                RSSItem _item = new RSSItem();




                NodeList nchild = currentNode.getChildNodes();
                int clength = nchild.getLength();


                for (int j = 1; j < clength; j = j + 2) {

                    Node thisNode = nchild.item(j);
                    String nodeContent = null;
                    String nodeName = thisNode.getNodeName();


                    nodeContent = nchild.item(j).getFirstChild().getNodeValue();

在 logcat 它告诉我这一行:

nodeContent = nchild.item(j).getFirstChild().getNodeValue();

是 NullPointerException 的原因,但正如我之前所说,如果提要没有<enclosure>标签,它就可以正常工作。

所以总结一下,如果XML文件有<enclosure>标签,就会导致应用程序不再工作。但是没有标签,它工作正常。我想要做的是要么忽略标签,要么(正确地)删除它,然后继续解析文档的其余部分。
目前没有什么对我有用,这就是我在这里问的原因。

任何帮助将不胜感激。

4

1 回答 1

3

好吧,是的-您要询问 . 的每个子节点的第一个子节点的值item

enclosure节点没有任何子节点,因此返回getFirstChildnull,如下所述:

此节点的第一个子节点。如果没有这样的节点,则返回 null。

So it's fine to call getFirstChild() on any node, but you should then check whether the value is null before you call getNodeValue().

于 2013-01-27T15:46:52.893 回答