2016-11-18 2 views
1

XOM Java 라이브러리를 사용하여 an RSS field을 구문 분석하려고합니다. 각 항목의 이미지 URL은 아래와 같이 <img> 요소의 속성으로 저장됩니다. .getFirstChildElement("img")<img src=""> 구문 분석을 시도 는XOM으로 요소 속성을 구문 분석 할 수 없습니다.

<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= ...>를 검색 할 때 내 코드 충돌을, 널 포인터를 반환한다. 내 프로그램이 <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); 
     } 
    } 
} 

답변

0

항목에 img 요소가 없습니다. 어떤 항목을 포함하는 것은 이것이다

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

보십시오 : IMG의 elment 아니다

<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> 

합니다. 일반 텍스트입니다.

+0

이것은 'img src ='를 구문 분석 할 수 없다는 문제를 해결하지 못합니다. –

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