无法使用XOM解析元素属性

时间:2016-11-18 22:49:56

标签: java rss xom

我正在尝试使用an RSS field Java库解析XOM。每个条目的图像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);
        }
    }
}

2 个答案:

答案 0 :(得分: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>

这不是一种模仿。这是纯文本。

答案 1 :(得分:0)

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

// 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 );
    }
}