无法使用Java和Sax解析一些RSS提要

时间:2010-05-29 05:28:04

标签: java android rss parsing sax

我用Java编写了一个RSS提要解析器(在Android上运行),它完全解析了一些提要,而其他提取则完全没有。尝试解析Slashdot(http://rss.slashdot.org/Slashdot/slashdot

时出现以下错误
org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 0: unbound prefix

如果我尝试解析有线(http://feeds.wired.com/wired/index

org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 0: syntax error

如果我尝试解析AndroidGuys(http://feeds.feedburner.com/androidguyscom

org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 0: syntax error

以下是我的解析器的一些代码。

public void updateArticles(Context ctx, Feed feed, int numDaysToGet) {
    try {
        targetFlag = TARGET_ARTICLES;
        tweetDB = new TweetMonsterDBAdapter(ctx);
        tweetDB.open();
        currentFeed = feed;
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));  // or "Etc/GMT-1"

        Date currentDate = new Date();
        long dateInMillis = currentDate.getTime();
        oldestDate.setTime(dateInMillis-(dayInMillis*numDaysToGet));

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(this);
        xr.parse(new InputSource(currentFeed.url.openStream()));

    } catch (IOException e) {
        Log.e("TweetMonster", e.toString());
    } catch (SAXException e) {
        tweetDB.close();
        Log.e("TweetMonster", e.toString());
    } catch (ParserConfigurationException e) {
        Log.e("TweetMonster", e.toString());
    }
    tweetDB.close();
}

它甚至没有进入我的startElement方法。

2 个答案:

答案 0 :(得分:2)

如果您想解决此类问题,我建议您从服务器打印响应。我之前得到了“ExpatParser $ ParseException:第1行,第0列:语法错误”,当我配置HttpClient不遵循重定向时,收到的响应类似于“此页面已移动”而不是所需的XML。

您可以执行以下操作:

BufferedReader br = new BufferedReader(new InputStreamReader(currentFeed.url.openStream()));
String str = null;

while ((str = br.readLine()) != null) 
   System.out.println(str);

只是为了看看实际上是什么回应。

答案 1 :(得分:1)

如果它对其他人有帮助,我也会从iPhone端口弹出到Android的完全相同的错误消息,只是因为XML缺少未注册类型的XML顶部的声明行。

e.g。对于在{XML>中找到的blah类型标记,如

<blah:abc>content</blah:abc>

我们需要以下内容......

<parentelement xmlns:blah="http://www.blah.com/dtds/blah.dtd" version="2.0" >
   <blah:abc>content</blah:abc>
</parentelement>

如果它在外部RSS源中,您无法控制,您可以读取文件内容并在正常运行解析器之前附加相关的缺失文本,同时还联系RSS生产者以要求他们符合标准