簡體   English   中英

確定Feed是Atom還是RSS

[英]Determining whether a feed is Atom or RSS

我正在嘗試確定給定的Feed是基於Atom還是基於RSS。

這是我的代碼:

public boolean isRSS(String URL) throws ParserConfigurationException, SAXException, IOException{
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document doc = builder
                .parse(URL);
        return doc.getDocumentElement().getNodeName().equalsIgnoreCase() == "rss";
    }

有沒有更好的方法呢? 如果我使用SAX Parser會更好嗎?

根元素是確定Feed類型的最簡單方法。

  • RSS提要有根元素rss (參見規范
  • Atom提要有根元素feed (參見規范

對於不同的Parsers,有不同的方法來獲取根元素。 沒有人比另一個人差。 關於StAX vs. SAX vs. DOM等已有足夠的文章,可以作為特定決策的基礎。

前兩行代碼沒有任何問題:

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(URL);

在return語句中,您在Java String比較中犯了一個錯誤。

當您使用比較運算符== with Strings時,它會比較引用而不是值(即檢查兩者是否完全相同)。 你應該在這里使用equals()方法。 只是為了確保我建議使用equalsIgnoreCase()

return doc.getDocumentElement().getNodeName().equalsIgnoreCase("rss");

提示:如果在isRss()方法中檢查“rss”而不是“feed”(如Atom),則不必使用三元運算符。

嗅探內容是一種方法。 但請注意,atom使用名稱空間,並且您正在創建非名稱空間感知解析器。

public boolean isAtom(String URL) throws ParserConfigurationException, SAXException, IOException{
    DocumentBuilderFactory f = DocumentBuilderFActory.newInstance();
    f.setNamespaceAware(true);
    DocumentBuilder builder = f.newInstance().newDocumentBuilder();
    Document doc = builder.parse(URL);
    Element e = doc.getDocumentElement(); 
    return e.getLocalName().equals("feed") && 
            e.getNamespaceURI().equals("http://www.w3.org/2005/Atom");
}

另請注意,您無法使用equalsIgnorCase()進行比較,因為XML元素名稱區分大小寫。

另一種方法是對Content-Type標頭作出反應,如果它在HTTP GET請求中可用。 ATOM的Content-Type是application/atom+xml和RSS application/rss+xml 但我懷疑,並非所有RSS提要都可以信任,以正確設置此標頭。

第三種選擇是查看URL后綴,例如.atom和.rss。

如果您使用的是Spring或JAX-RS,則可以輕松配置最后兩種方法

您可以使用StAX解析器來避免將整個XML文檔解析到內存中:

public boolean isAtom(String url) throws ParserConfigurationException, SAXException, IOException{
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new URL(url).openConnection());
    xsr.nextTag();  // Advance to root element
    return xsr.getLocalName().equals("feed") && 
            xsr.getNamespaceURI().equals("http://www.w3.org/2005/Atom");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM