Parsing XML namespaces?

By | January 12, 2018
Questions:

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.

Answers:

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

Leave a Reply

Your email address will not be published. Required fields are marked *