E4X XML Namespaces

For XML that looks like the following response from Yahoo’s weather service:
< ?xml version=’1.0′ encoding=’UTF-8′?>
http://weather.yahoo.com/forecast/94089_f.html Yahoo! Weather for Sunnyvale, CA
Tue, 06 Nov 2007 6:56 pm PST


http://weather.yahoo.com/ http://l.yimg.com/us.yimg.com/i/us/nws/th/main_142b.gif

http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/94089_f.html Tue, 06 Nov 2007 6:56 pm PST

< ![CDATA[

Current Conditions:
Fair, 55 F

Tue – Mostly Clear. High: 67 Low: 49
Wed – Partly Cloudy. High: 71 Low: 49

Full Forecast at Yahoo! Weather
(provided by The Weather Channel)



When you need to access the nodes with complex node names such as yweather:location think XML namespaces.
In the above example, look for the xmlns declaration in the rss node
Creating a Namespace object using the declaration will allow us to access the nodes with complex names.
Creating a Namespace object is a pretty simple process:

var yweatherNS:Namespace = new Namespace( http://xml.weather.yahoo.com/ns/rss/1.0 );

Now we can access the node with the following code:


trace( yahooWeaterXML.channel.yweatherNS::location.@city ); // outputs ‘Sunnyvale’
trace( yahooWeaterXML.channel.yweatherNS::location.@region); // outputs ‘CA’
trace( yahooWeaterXML.channel.yweatherNS::location.@country ); // outputs ‘US’

With the preceding example we need to know the namespace url ahead of time. E4X gives us the namespaceDeclarations() method that will return an array that contains the namespace declarations associated with the XML document

Using the namespaceDeclarations() method from the XML object:

var namespaces:Array = myXML.namespaceDeclarations();

Now we have an array of namespace declarations that we can use to dynamically declare Namespace objects and access our complex node names:

var yweatherNS:Namespace
var geoNS:Namespace
var nsLen:uint = nameSpaces.length;
for(var i:uint = 0; i < nsLen; i++)
var newNamespace:Namespace = new Namespace( nameSpaces[i] );
if( String( nameSpaces[i].prefix ).toLowerCase() == “yweather” )
yweatherNS = newNamespace;
geoNS = newNamespace;

So we can access the geo and yweather nodes without any problems now.