Working with XML Namespaces in Flash
Today I was having some issues with parsing RSS/ATOM feeds in Flash. I forgot to factor in the fact that both use namespaces in the XML. Here's a simple block of code I used to handle the namespaces and parse the XML into Value Objects:
public function xmlLoaded(event:Event):void
{
trace("done loading");
theXML = XML(myLoader.data);
var ns:Namespace = theXML.namespace();
for each (var property:XML in theXML..item)
{
var atom:Namespace = property.namespace("atom");
var fVO:FeatureVO = new FeatureVO();
fVO.pubDate = property.pubDate;
fVO.updated = property.atom::updated;
fVO.category = property.category;
fVO.title = property.title;
fVO.summary = property.atom::summary;
fVO.link = property.link;
fVO.enclosure = property.enclosure.@url;
fVO.xmlData = property;
model.featuresArray.push(fVO);
trace("creating featureVO "+fVO.enclosure);
}
This is what the sample xml looked like from Blogger's RSS/ATOM feed:
<rss xmlns:atom='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' version='2.0'>
<channel>
<atom:id>tag:blogger.com,1999:blog-</atom:id>
<lastBuildDate>Wed, 10 Sep 2008 19:07:53 +0000</lastBuildDate>
<title></title>
<description></description>
<link>asdfasdf.com/</link>
<managingEditor>noreply@blogger.com (Erik Loehfelm)</managingEditor>
<generator>Blogger</generator>
<openSearch:totalResults>9</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<item>
<guid isPermaLink='false'>tag:blogger.com,1999:blog-</guid>
<pubDate>Wed, 10 Sep 2008 19:07:00 +0000</pubDate>
<atom:updated>2008-09-10T15:07:53.696-04:00</atom:updated>
<category domain='http://www.blogger.com/atom/ns#'>feature</category>
<title>People Singing</title>
<atom:summary>This is going to be a feature for the portal.v/atom:summary>
<link>asdfasdfasdf.html</link>
<enclosure type='image/jpeg' url='http://msnbcmedia.msn.com/j/msnbc/Components/Slideshows/_production/ss-080522-idolfinale/ss-080522-idolfinale-09.hmedium.jpg' length='0'/>
<author>noreply@blogger.com (Erik Loehfelm)</author>
</item>
</channel>
</rss>
You can see the syntax to be used on the 2 lines highlighted in bold above. The first defines the namespace (atom) and the second shows how you access elements in the xml that have the atom namespace applied to them.