1

我正在尝试使用XOM Java 库解析RSS 字段。每个条目的图像 URL 都存储为元素的属性,如下所示。 <img>

<rss version="2.0">
  <channel>
    <item>
      <title>Decision Paralysis</title>
      <link>https://xkcd.com/1801/</link>
      <description>
        <img src="https://imgs.xkcd.com/comics/decision_paralysis.png"/>
      </description>
      <pubDate>Mon, 20 Feb 2017 05:00:00 -0000</pubDate>
      <guid>https://xkcd.com/1801/</guid>
    </item>
  </channel>
</rss>

尝试解析<img src="">.getFirstChildElement("img")只返回一个空指针,当我尝试检索<img src= ...>. 为什么我的程序无法读取<img>元素,如何正确读取它?

import nu.xom.*;

public class RSSParser {
    public static void main() {
        try {
            Builder parser = new Builder();
            Document doc = parser.build ( "https://xkcd.com/rss.xml" );
            Element rootElement = doc.getRootElement();
            Element channelElement = rootElement.getFirstChildElement("channel");
            Elements itemList = channelElement.getChildElements("item");

            // Iterate through itemList
            for (int i = 0; i < itemList.size(); i++) {
                Element item = itemList.get(i);
                Element descElement = item.getFirstChildElement("description");
                Element imgElement = descElement.getFirstChildElement("img");
                // Crashes with NullPointerException
                String imgSrc = imgElement.getAttributeValue("src");
            }
        }
        catch (Exception error) {
            error.printStackTrace();
            System.exit(1);
        }
    }
}
4

2 回答 2

0

我设法使用正则表达式和模式匹配提出了一个有点老套的解决方案。

// Iterate through itemList
for (int i = 0; i < itemList.size(); i++) {
    Element item = itemList.get(i);
    String descString = item.getFirstChildElement("description").getValue();

    // Parse image URL (hacky)
    String imgSrc = "";
    Pattern pattern = Pattern.compile("src=\"[^\"]*\"");
    Matcher matcher = pattern.matcher(descString);
    if (matcher.find()) {
        imgSrc = descString.substring( matcher.start()+5, matcher.end()-1 );
    }
}
于 2017-02-17T16:20:20.707 回答
0

项目中没有 img 元素。尝试

  if (imgElement != null) {
    String imgSrc = imgElement.getAttributeValue("src");
  }

该项目包含的是这样的:

<description>&lt;img    
    src="http://imgs.xkcd.com/comics/us_state_names.png" 
    title="Technically DC isn't a state, but no one is too 
    pedantic about it because they don't want to disturb the snakes
    ." 
     alt="Technically DC isn't a state, but no one is too pedantic about it because they don't want to disturb the snakes." /&gt;  
</description>

那不是一个图像元素。是纯文本。

于 2016-11-30T23:11:42.373 回答