This subject has been touched on before, but there’s been some time since the last question regarding namespace handling.
Is there a cross-browser solution to get the elements by name in Javascript?
<?xml version="1.0" encoding="UTF-8"?>
<NS:response success="1" xmlns:NS="http://someURI/ns">
<NS:user firstname="foo" lastname="bar"></NS:user>
<NS:cookie value="2c0ea35bcac2e05d439609367a236b28" name="session"></NS:cookie>
</NS:response>
So far what I’ve got:
var oXML = (new DOMParser()).parseFromString(xmlstring, "text/xml");
var root = oXML.documentElement;
var user = typeof(user=root.getElementsByTagName(root.prefix + ':user')[0]) === "undefined"
?root.getElementsByTagName('user')[0]
:user;
Hasn’t been tested in IE, but if anyone has any cross-browser solution, I’d be willing to hear.
Other Considerations:
- getElementsByTagNameNS() – am trying to avoid having to specify the namespace/uri
- using regex to strip the namespace before creating the XML document
- not using a namespace – I have that option, but would not like to go that route
You could try another approach, by converting the XML to JSON server side, using a generic XSLT like http://code.google.com/p/xml2json-xslt/, and deliver to the browser only JSON.
It will add up a small overhead on the server response, but nothing compared to the amount of code and time spent on the browser to render XML.
With the exception of IE, with its impressive msxml, I think reading XML in common browsers is a real pain compared to JSON.