2011-12-24 56 views
0

我從一個網站獲取Rss。在描述標籤中有一張我想要展示給用戶的圖片。我米使用此代碼來獲得它:從Rss獲取圖像 - 最好的方法嗎?

public void setDescription(String description) { 
     this.description = description; 
     //parse description for any image or video links 
     if (description.contains("<img style=")){ 
      String imgg = description.substring(description.indexOf("<img style=")); 
      String cleanUp = imgg.substring(0, imgg.indexOf(">")+1); 
      imgg = imgg.substring(imgg.indexOf("src=") + 5); 
      int indexOf = imgg.indexOf("\""); 
      if (indexOf==-1){ 
       indexOf = imgg.indexOf("\""); 
      } 
      imgg = imgg.substring(0, indexOf); 

      setImgLink(imgg); 

      this.description = this.description.replace(cleanUp, ""); 
     } else{ 

      String imgg2="replace_image.png"; 
      setImgLink(imgg2); 
     } 

    } 

我的問題是,如果該網站即時得到的RSS在XML改變的東西,即時得到我更換形象方面舉例來說,如果img樣式改變圖片src或者類似的東西。

有沒有什麼辦法解決它,並獲取每次從描述圖像? 我發現我可以使用這樣的事情,但我不能讓它工作http://developer.android.com/reference/android/text/Html.html

謝謝!:)

回答

0

而不是使用正則表達式它能夠更好地使用DOM和XPath提取圖像源。即使HTML發生變化,這種方式仍然可以解決您的問題。

看來你在description中有描述,你需要圖片路徑在imgg。試試這個:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
builderFactory.setNamespaceAware(true); 
DocumentBuilder builder = builderFactory.newDocumentBuilder(); 
Document document = builder.parse(description); 

XPath xpath = XPathFactory.newInstance().newXPath(); 
String expression = "//img"; 
Node imgNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); 

String imgg = imgNode.getAttribute("src"); 
+1

什麼是節點導入(我的意思是庫)?這是一個進口org.w3c.dom.Node; – maverickosama92 2013-12-10 07:28:20

+1

請指定正在使用的庫。我無法在w3c節點中找到'getAttribute'。 – 2014-03-26 14:18:17

+0

'getAttribute(String)方法未定義類型Node' – 2015-12-06 19:41:14