ploem.be blog

How to … parse an Atom feed in flash

"A while ago adobe released their as3syndicationlib for easy access to RSS & Atom feeds by converting either RSS 1.0/2.0 or Atom feeds into generic data accessible via the IFeed interface. These libraries also require adobe's corelib."

This is what I used to create my little jesusontwitter example. Download these 2 libs and add them to your project. I also used the twitter search API (search API).

Now let's see what I did first:

//url of atom feed
private static const ATOM_URL:String = "http://search.twitter.com/search.atom?q=jesus〈=en&rpp=40";

Here I enter the url to atom feed that I get from the twitter search API. So I search for Jesus, the results must be in english and I want to get the last 40 tweets back.

private function loadXML():void{
loader = new URLLoader();
//request pointing to feed
var request:URLRequest = new URLRequest(ATOM_URL);
request.method = URLRequestMethod.GET;
//listen for when the data loads
loader.addEventListener(Event.COMPLETE, onDataLoad);
//listen for error events
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
//load the feed data
loader.load(request);
}

This part speaks for itself, we listen to the event.complete of the XML to load (and to be sure we also add a listener to the IOErrorEvent and the SecurityErrorEvent in case something goes wrong). Loader.load our request and that's it.

private function onDataLoad(e:Event):void{
trace("onXmlLoaded");
//get the raw string data from the feed
var rawAtom:String = URLLoader(e.target).data;
//parse it as Atom
parseAtom(rawAtom);
}

When the data is loaded we get the RAW string and pass it on to be parsed by our own method.

//parses the Atom feed
private function parseAtom(data:String):void
{
//XMLSyndicationLibrary does not validate that the data contains valid
//XML, so you need to validate that the data is valid XML.
//We use the XMLUtil.isValidXML API from the corelib library.
if(!XMLUtil.isValidXML(data))
{
trace("Feed does not contain valid XML.");
return;
}
//create Atom10 instance
var atomfeed:Atom10 = new Atom10();
//parse the raw atom data
atomfeed.parse(data);
//get all of the items within the feed
items = atomfeed.entries;
showTweetsStart();
}

We gather all the atomfeed entries in the items array. This is our collection of data objects.

Now we can for example get the content of the tweet:

var currentEntry:Entry = items[currentindex];
if(currentEntry.title != null && currentEntry.title != ""){
tweet_label.text = currentEntry.title;
}else{
tweet_label.text = "God damned! Bad tweet!"
}

We get one Entry of the items array and pass the title on to a textfield. Wohoew! We're done. Happy atom feeding!