Loading a RSS XML feed just using JavaSript

Continuating the post Manipulating XML using JavaScript, now a util example of XML + JavaScript: Loading a RSS XML feed.

1) Manipulating XML using JavaScript

See my previous small tutorial about XML + JavaScript to understend the function above.

2) Making the function to read RSS data

Put the JavaScript function above in your html document or in a ".js" file (and include in your document).

function xmlMicoxRSS(xmlNode){
 //by Micox: http://elmicoxcodes.blogspot.com
 var retorno = "";
 var objNodeList = xmlNode.getElementsByTagName("item")
 for(var i=0;i<objNodeList.length;i++){
  var strTitulo = ""
  var strURL = ""
  var strDescr = ""
  var objNode = objNodeList[i];
  if(objNode.nodeType == 1){//ignore white spaces
   for(var j=0;j<objNode.childNodes.length;j++){
    var objNode2 = objNode.childNodes[j];
    if(objNode2.nodeType == 1){//ignore white spaces
     switch (objNode2.nodeName) {
      case "title": 
       //alert(objNode.childNodes[j].firstChild.nodevalue);
       strTitulo = objNode2.firstChild.nodeValue; 
       break;
      case "link": 
       strURL = objNode2.firstChild.nodeValue; 
       break;
      case "description": 
       strDescr = objNode2.firstChild.nodeValue; 
       break;
     }
    }
   }
   retorno += " <li><a href='" + strURL + "'>" + strTitulo + "</a><br />" + strDescr + "</li>\n";
  }
 }
 retorno = "<ul>\n" + retorno + "</ul>";
 return retorno;
}

3) Now, put the return to your DIV

First, call the function xmlMicoxLoader (previous post) and give to div the return of function xmlMicoxRSS.

xml = xmlMicoxLoader("rss.xml"); //load xml
document.getElementById(div_alvo).innerHTML = xmlMicoxRSS(xml); //list rss

Important: JavaScript just load file in your domain for security reasons.

Another example of XML + Javascript: Dynamic Graphs with Ajax and XML.

Bugs, tests and doubts, comment here :) Sorry my bad english.

3 comments:

  1. Nice info..thank you for your work

    ReplyDelete
  2. I need this code to work inside a blogger page and get XML from another site.

    I tried everything but I get access denied.

    But blogger uses a similar way to get external feeds.

    Does anybody know how does blogger do it ?

    ReplyDelete
  3. Hi zibri,

    by security reasons, browsers dont give access to javascript access external domains. becouse of this, that you receive 'access denied' message.

    the blogger effect uses server-side programation. In server-side programation (asp, php, jsp, etc) you will get another site.

    thanks.

    ReplyDelete