Cómo analizar un feed RSS usando JavaScript?

Necesito analizar una fuente RSS (XML versión 2.0) y mostrar los detalles analizados en una página HTML.

Analizando el Feed

Con jQuery ‘s jFeed

(Realmente no lo recomiendo, vea las otras opciones).

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

Con el soporte XML integrado de jQuery

 $.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()); }); }); 

Con jQuery y la API de Google AJAX Feed

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

Pero eso significa que estás seguro de que están en línea y accesibles.


Crear contenido

Una vez que haya extraído con éxito la información que necesita del feed, podría crear DocumentFragment s (con document.createDocumentFragment() contiene los elementos (creados con document.createElement() ) que desea inyectar para mostrar sus datos.


Inyectando el contenido

Seleccione el elemento contenedor que desee en la página y anexe los fragmentos de su documento, y simplemente use innerHTML para reemplazar su contenido por completo.

Algo como:

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

o:

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

Datos de prueba

Usando el feed de esta pregunta , que a partir de este escrito da:

 < ?xml version="1.0" encoding="utf-8"?>  How to parse a RSS feed using javascript? - Stack Overflow    most recent 30 from stackoverflow.com 2012-06-08T06:36:47Z https://stackoverflow.com/feeds/question/10943544 http://www.creativecommons.org/licenses/by-sa/3.0/rdf  https://stackoverflow.com/q/10943544 2 How to parse a RSS feed using javascript?   Thiru https://stackoverflow.com/users/1126255   2012-06-08T05:34:16Z 2012-06-08T06:35:22Z  <p>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't know whether it is possible or not. If any one knows please help me on this. Thanks in advance.</p>    https://stackoverflow.com/questions/10943544/-/10943610#10943610 1 Answer by haylem for How to parse a RSS feed using javascript?  haylem https://stackoverflow.com/users/453590   2012-06-08T05:43:24Z 2012-06-08T06:35:22Z <h1>Parsing the Feed</h1> <h3>With jQuery's jFeed</h3> <p>Try this, with the <a href="http://plugins.jquery.com/project/jFeed" rel="nofollow">jFeed</a> <a href="http://www.jquery.com/" rel="nofollow">jQuery</a> plug-in</p> <pre><code>jQuery.getFeed({ url : FEED_URL, success : function (feed) { console.log(feed.title); // do more stuff here } }); </code></pre> <h3>With jQuery's Built-in XML Support</h3> <pre><code>$.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()); }); }); </code></pre> <h3>With jQuery and the Google AJAX APIs</h3> <p>Otherwise, <a href="https://developers.google.com/feed/" rel="nofollow">Google's AJAX Feed API</a> allows you to get the feed as a JSON object:</p> <pre><code>$.ajax({ url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=10&amp;callback=?&amp;q=' + encodeURIComponent(FEED_URL), dataType : 'json', success : function (data) { if (data.responseData.feed &amp;&amp; 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); }); } } }); </code></pre> <p>But that means you're relient on them being online and reachable.</p> <hr> <h1>Building Content</h1> <p>Once you've successfully extracted the information you need from the feed, you need to create document fragments containing the elements you'll want to inject to display your data.</p> <hr> <h1>Injecting the content</h1> <p>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.</p>   

Ejecuciones

Uso del soporte XML integrado de jQuery

Invocar:

 $.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()); }); }); 

Imprime:

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

Usando jQuery y las API de Google AJAX

Invocar:

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

Imprime:

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

Otra opción obsoleta (gracias a @daylight) , y la más fácil para mí (esto es lo que estoy usando para SpokenToday.info ):

La API de Google Feed sin usar JQuery y con solo 2 pasos:

  1. Importar la biblioteca:

       
  2. Buscar / cargar feeds ( documentación ):

     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. Para analizar datos, consulte la documentación sobre el formato de respuesta .

Si está buscando una alternativa simple y gratuita a Google Feed API para su widget rss, rss2json.com podría ser una solución adecuada para eso.

Puede intentar ver cómo funciona en un código de muestra de la documentación de la API a continuación:

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

Result from the API: