ASP XML Feed Proxy

It’s relatively easy to write an XML Feed Proxy script with your favourite scripting language. But why would you want to do this?

I found the answer recently while working on an AJAX Grid code sample for this website:

Because of security issues, client-side javascript will not allow you to place an XMLHttpRequest to a website other than the one your client-side script resides on. So, if you were hoping to consume, let’s say, your LiveJournal feed from your personal website via XMLHttpRequest, you’re outta luck.

So, the workaround is to write a server-side script that retrieves the XML feed for you, and displays it as a feed coming from your own website.

For example, let's look at this proxy of my brother Andy’s Yahoo 360 blog feed (RSS 2.0). The code in Classic ASP (Javascript) looks like this:

<script language="JavaScript" runat="server">
  Response.ContentType = "text/xml";
    // rssURL is set to the path to my brother Andy's Yahoo 360 RSS feed...
    var rssUrl = "http://blog.360.yahoo.com/rss-mw6Ml_84drYuYJ8uundv5uFUvLFwpjD6";
    var xml = new ActiveXObject("MSXML2.DomDocument.4.0");
    xml.setProperty("ServerHTTPRequest", true);
    xml.async = false;			
    xml.validateOnParse = true;
// if something goes wrong, we'll send out an XML-formatted error response. if (xml.parseError.errorCode != 0) { xmlError = new Error(); xmlError.Message = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xmlError.Message += "<error>"; xmlError.Message += "<description>"; xmlError.Message += "Error parsing feed: " + xml.parseError.reason; xmlError.Message += "</description>"; xmlError.Message += "</error>"; throw(xmlError); }
// Handily, we can simply save the XML to the Response stream in ASP. xml.save(Response); } catch(e) { Response.Write(e.Message); } </script>

Pretty Simple, eh?

One thing to always keep in mind is that the script will fail if the other site is down, or having server problems... also, if the other site is slow to respond, the script will take longer to render the XML. You will want to account for these possibilities.