views:

283

answers:

1

Using JavaScript/Ajax?

I'm trying to extract values from:

<yweather:astronomy sunrise="6:34 am"   sunset="8:38 pm"/>

Looking for something like:

var response = transport.responseXML.getElementsByTagName("channel");
sunrise = response[0].getElementsByTagName("yweather:astronomy").item(0).Attributes["sunrise"].Value;

But nothing works so far. :'( Thanks.

+3  A: 

There is a special version of getElementsByTagName for namespaces: getElementsByTagNameNS.

For example:

var response = transport.responseXML.getElementsByTagName("channel");
var sunrise = response[0].getElementsByTagNameNS("[Namespace URI]", "astronomy")[0].getAttribute("sunrise");

...where [Namespace URI] is the URI of the yweather namespace.

Steve

Steve Harrison
Not supported by IE, but correct otherwise
annakata
@annakata: Out of interest, how can do you do it in IE?
Steve Harrison
I think you can just use getElementsByTagName("yweather:astronomy") with IE. Also, Google feeds API has a cross browser implementation. Maybe you can use that, or something like it: http://code.google.com/apis/ajaxfeeds/documentation/reference.html#getElementsByTagNameNS
dylanfm
In MSXML, you can set the "SelectionNamespaces" property on the XML DOMDocument object, then use the non-standard "selectNodes" (or "selectSingleNode") method with an XPath selector. See http://www.xml.com/pub/a/2002/06/05/msxml4.html for an example.
NickFitz
@NickFitz: Ah, I see. Thanks!
Steve Harrison