121

我需要解析 RSS 提要(XML 2.0 版)并在 HTML 页面中显示解析的详细信息。

4

9 回答 9

220

解析提要

使用jQueryjFeed

(真的不推荐那个,请参阅其他选项。)

jQuery.getFeed({
   url     : FEED_URL,
   success : function (feed) {
      console.log(feed.title);
      // do more stuff here
   }
});

使用jQuery的内置 XML 支持

$.get(FEED_URL, function (data) {
    $(data).find("entry").each(function () { // or "item" or whatever suits your feed
        var el = $(this);

        console.log("------------------------");
        console.log("title      : " + el.find("title").text());
        console.log("author     : " + el.find("author").text());
        console.log("description: " + el.find("description").text());
    });
});

使用jQueryGoogle AJAX Feed API

$.ajax({
  url      : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
  dataType : 'json',
  success  : function (data) {
    if (data.responseData.feed && data.responseData.feed.entries) {
      $.each(data.responseData.feed.entries, function (i, e) {
        console.log("------------------------");
        console.log("title      : " + e.title);
        console.log("author     : " + e.author);
        console.log("description: " + e.description);
      });
    }
  }
});

但这意味着您依赖他们在线且可访问。


建筑内容

从提要中成功提取所需信息后,您可以创建DocumentFragments (其中包含要注入document.createDocumentFragment()的元素(使用 创建)以显示数据。document.createElement()


注入内容

在页面上选择您想要的容器元素并将您的文档片段附加到它,然后简单地使用 innerHTML 来完全替换其内容。

就像是:

$('#rss-viewer').append(aDocumentFragmentEntry);

或者:

$('#rss-viewer')[0].innerHTML = aDocumentFragmentOfAllEntries.innerHTML;

测试数据

使用这个问题的提要,在撰写本文时给出:

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0">
    <title type="text">How to parse a RSS feed using javascript? - Stack Overflow</title>
    <link rel="self" href="https://stackoverflow.com/feeds/question/10943544" type="application/atom+xml" />
        <link rel="hub" href="http://pubsubhubbub.appspot.com/" />        
    <link rel="alternate" href="https://stackoverflow.com/q/10943544" type="text/html" />
    <subtitle>most recent 30 from stackoverflow.com</subtitle>
    <updated>2012-06-08T06:36:47Z</updated>
    <id>https://stackoverflow.com/feeds/question/10943544</id>
    <creativeCommons:license>http://www.creativecommons.org/licenses/by-sa/3.0/rdf</creativeCommons:license> 
    <entry>
        <id>https://stackoverflow.com/q/10943544</id>
        <re:rank scheme="http://stackoverflow.com">2</re:rank>
        <title type="text">How to parse a RSS feed using javascript?</title>
        <category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="javascript"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="html5"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="jquery-mobile"/>
        <author>
            <name>Thiru</name>
            <uri>https://stackoverflow.com/users/1126255</uri>
        </author>
        <link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript" />
        <published>2012-06-08T05:34:16Z</published>
        <updated>2012-06-08T06:35:22Z</updated>
        <summary type="html">
            &lt;p&gt;I need to parse the RSS-Feed(XML version2.0) using XML and I want to display the parsed detail in HTML page, I tried in many ways. But its not working. My system is running under proxy, since I am new to this field, I don&#39;t know whether it is possible or not. If any one knows please help me on this. Thanks in advance.&lt;/p&gt;

        </summary>
    </entry>
    <entry>
        <id>https://stackoverflow.com/questions/10943544/-/10943610#10943610</id>
        <re:rank scheme="http://stackoverflow.com">1</re:rank>
        <title type="text">Answer by haylem for How to parse a RSS feed using javascript?</title>
        <author>
            <name>haylem</name>
            <uri>https://stackoverflow.com/users/453590</uri>
        </author>    
        <link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript/10943610#10943610" />
        <published>2012-06-08T05:43:24Z</published>   
        <updated>2012-06-08T06:35:22Z</updated>
        <summary type="html">&lt;h1&gt;Parsing the Feed&lt;/h1&gt;

&lt;h3&gt;With jQuery&#39;s jFeed&lt;/h3&gt;

&lt;p&gt;Try this, with the &lt;a href=&quot;http://plugins.jquery.com/project/jFeed&quot; rel=&quot;nofollow&quot;&gt;jFeed&lt;/a&gt; &lt;a href=&quot;http://www.jquery.com/&quot; rel=&quot;nofollow&quot;&gt;jQuery&lt;/a&gt; plug-in&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.getFeed({
   url     : FEED_URL,
   success : function (feed) {
      console.log(feed.title);
      // do more stuff here
   }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;With jQuery&#39;s Built-in XML Support&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;$.get(FEED_URL, function (data) {
    $(data).find(&quot;entry&quot;).each(function () { // or &quot;item&quot; or whatever suits your feed
        var el = $(this);

        console.log(&quot;------------------------&quot;);
        console.log(&quot;title      : &quot; + el.find(&quot;title&quot;).text());
        console.log(&quot;author     : &quot; + el.find(&quot;author&quot;).text());
        console.log(&quot;description: &quot; + el.find(&quot;description&quot;).text());
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;With jQuery and the Google AJAX APIs&lt;/h3&gt;

&lt;p&gt;Otherwise, &lt;a href=&quot;https://developers.google.com/feed/&quot; rel=&quot;nofollow&quot;&gt;Google&#39;s AJAX Feed API&lt;/a&gt; allows you to get the feed as a JSON object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$.ajax({
  url      : document.location.protocol + &#39;//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;amp;num=10&amp;amp;callback=?&amp;amp;q=&#39; + encodeURIComponent(FEED_URL),
  dataType : &#39;json&#39;,
  success  : function (data) {
    if (data.responseData.feed &amp;amp;&amp;amp; data.responseData.feed.entries) {
      $.each(data.responseData.feed.entries, function (i, e) {
        console.log(&quot;------------------------&quot;);
        console.log(&quot;title      : &quot; + e.title);
        console.log(&quot;author     : &quot; + e.author);
        console.log(&quot;description: &quot; + e.description);
      });
    }
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But that means you&#39;re relient on them being online and reachable.&lt;/p&gt;

&lt;hr&gt;

&lt;h1&gt;Building Content&lt;/h1&gt;

&lt;p&gt;Once you&#39;ve successfully extracted the information you need from the feed, you need to create document fragments containing the elements you&#39;ll want to inject to display your data.&lt;/p&gt;

&lt;hr&gt;

&lt;h1&gt;Injecting the content&lt;/h1&gt;

&lt;p&gt;Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.&lt;/p&gt;
</summary>
    </entry></feed>

处决

使用 jQuery 的内置 XML 支持

调用:

$.get('https://stackoverflow.com/feeds/question/10943544', function (data) {
    $(data).find("entry").each(function () { // or "item" or whatever suits your feed
        var el = $(this);

        console.log("------------------------");
        console.log("title      : " + el.find("title").text());
        console.log("author     : " + el.find("author").text());
        console.log("description: " + el.find("description").text());
    });
});

打印出来:

------------------------
title      : How to parse a RSS feed using javascript?
author     : 
            Thiru
            https://stackoverflow.com/users/1126255

description: 
------------------------
title      : Answer by haylem for How to parse a RSS feed using javascript?
author     : 
            haylem
            https://stackoverflow.com/users/453590

description: 

使用 jQuery 和 Google AJAX API

调用:

$.ajax({
  url      : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('https://stackoverflow.com/feeds/question/10943544'),
  dataType : 'json',
  success  : function (data) {
    if (data.responseData.feed && data.responseData.feed.entries) {
      $.each(data.responseData.feed.entries, function (i, e) {
        console.log("------------------------");
        console.log("title      : " + e.title);
        console.log("author     : " + e.author);
        console.log("description: " + e.description);
      });
    }
  }
});

打印出来:

------------------------
title      : How to parse a RSS feed using javascript?
author     : Thiru
description: undefined
------------------------
title      : Answer by haylem for How to parse a RSS feed using javascript?
author     : haylem
description: undefined
于 2012-06-08T05:43:24.190 回答
39

另一个已弃用 (感谢@daylight)选项,对我来说最简单(这是我用于SpokenToday.info的):

Google Feed API不使用 JQuery ,只需 2 个步骤:

  1. 导入库:

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">google.load("feeds", "1");</script>
    
  2. 查找/加载提要(文档):

    var feed = new google.feeds.Feed('http://www.google.com/trends/hottrends/atom/feed?pn=p1');
    feed.load(function (data) {
        // Parse data depending on the specified response format, default is JSON.
        console.dir(data);
    });
    
  3. 要解析数据,请查看有关响应格式的文档

于 2013-06-13T02:03:04.367 回答
4

不幸的是,对于其他阅读本文的人(从 2019 年开始),大多数 JS RSS 阅读实现现在都不起作用。首先,Google API 已经关闭,所以这不再是一个选项,并且由于 CORS 安全策略,您现在通常不能跨域请求 RSS 提要。

使用https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) 上的示例,我得到以下信息:

Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是正确的,并且是最终网站的安全预防措施,但现在确实意味着上述答案不太可能奏效。

我的解决方法可能是通过 PHP 解析 RSS 提要并允许 javascript 访问我的 PHP,而不是尝试访问最终目标提要本身。

于 2019-10-02T10:57:05.757 回答
4

如果您正在为您的 rss 小部件寻找一个简单且免费的Google Feed API替代方案,那么rss2json.com可能是一个合适的解决方案。

您可以尝试从以下api 文档中的示例代码中查看它是如何工作的:

google.load("feeds", "1");

    function initialize() {
      var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");
      feed.load(function(result) {
        if (!result.error) {
          var container = document.getElementById("feed");
          for (var i = 0; i < result.feed.entries.length; i++) {
            var entry = result.feed.entries[i];
            var div = document.createElement("div");
            div.appendChild(document.createTextNode(entry.title));
            container.appendChild(div);
          }
        }
      });
    }
    google.setOnLoadCallback(initialize);
<html>
  <head>    
     <script src="https://rss2json.com/gfapi.js"></script>
  </head>
  <body>
    <p><b>Result from the API:</b></p>
    <div id="feed"></div>
  </body>
</html>

于 2018-06-04T14:17:18.560 回答
2

我对许多误导性的文章和答案感到非常愤怒,以至于我编写了自己的 RSS 阅读器: https ://gouessej.wordpress.com/2020/06/28/comment-creer-un-lecteur-rss-en-javascript-how- to-create-a-rss-reader-in-javascript/

您可以使用 AJAX 请求来获取 RSS 文件,但当且仅当您使用 CORS 代理时它才会起作用。我将尝试编写自己的 CORS 代理,为您提供更强大的解决方案。与此同时,它可以工作,我将它部署在我的 Debian Linux 下的服务器上。

我的解决方案不使用 JQuery,我只使用普通的 Javascript 标准 API,没有第三方库,它应该可以与 Microsoft Internet Explorer 11 一起使用。

于 2020-06-28T12:42:24.500 回答
2

如果你想使用纯 JavaScript API,在https://github.com/hongkiat/js-rss-reader/有一个很好的例子

https://www.hongkiat.com/blog/rss-reader-in-javascript/上的完整描述

它使用fetch方法作为异步获取资源的全局方法。下面是一段代码:

fetch(websiteUrl).then((res) => {
  res.text().then((htmlTxt) => {
    var domParser = new DOMParser()
    let doc = domParser.parseFromString(htmlTxt, 'text/html')
    var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
  })
}).catch(() => console.error('Error in fetching the website'))
于 2018-09-09T05:43:41.117 回答
0

您可以使用jquery-rssVanilla RSS,它们带有漂亮的模板并且非常易于使用:

// Example for jquery.rss
$("#your-div").rss("https://stackoverflow.com/feeds/question/10943544", {
    limit: 3,
    layoutTemplate: '<ul class="inline">{entries}</ul>',
    entryTemplate: '<li><a href="{url}">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'
})

// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
    document.querySelector("#your-div"),
    "https://stackoverflow.com/feeds/question/10943544",
    { 
      // options go here
    }
);
rss.render().then(() => {
  console.log('Everything is loaded and rendered');
});

有关工作示例,请参阅http://jsfiddle.net/sdepold/ozq2dn9e/1/ 。

于 2019-10-16T10:23:31.327 回答
0

现在试图找到一个好的解决方案,我偶然发现了FeedEk jQuery RSS/ATOM Feed 插件,它通过 jQuery Feed API很好地解析和显示 RSS 和 Atom 提要。对于一个基本的基于 XML 的 RSS 提要,我发现它就像一个魅力,不需要服务器端脚本或其他 CORS 变通方法,它甚至可以在本地运行。

于 2019-11-11T16:26:49.200 回答
0

由于我不断收到 CORS 错误,我没有找到仅使用 js 解析 RSS 的解决方案。安装插件对我来说不是一个选项,构建代理也不好玩,我发现的小解决方案也不起作用。

因此,以防万一有人来到这里并可以使用服务器端,我发现这个PHP 解决方案非常适合我!(没有 CORS 错误!“x 已被 CORS 策略阻止...”)

于 2021-09-01T22:28:24.100 回答