1

我正在尝试“获取”一个 RSS 提要。

 public RssFeed(String url) {
    _url = url;
    String res = this.api.get(url);
    ByteArrayInputStream bis = new ByteArrayInputStream(res.getBytes());

    try {
        bis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    XMLDecoder decoder = new XMLDecoder(bis);
    try {
        Object xml = decoder.readObject();
        _response = xml.toString();
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        decoder.close();
    }
}

当我检查“res”里面的内容时。它似乎得到了整个 XML。但是,我试图解码它,我得到:

java.lang.IllegalArgumentException: Unsupported element: rss

有人可以帮我吗?我是 Java 新手。

谢谢!

4

1 回答 1

1

XMLDecoder旨在用于由XMLEncoder. 由于您是从 Web 上抓取此 XML,因此根据这些类,此 XML 中的元素可能无效。使用更通用的 XML 解析器,例如DocumentBuilder::parse()处理此问题。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

try {
    builder.parse(url);
} catch (IOException e) {
    e.printStackTrace();
} catch (SAXParseException e) {
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    e.printStackTrace();
}
于 2018-02-09T18:00:35.957 回答