vol7ron
vol7ron

Reputation: 42149

Cross-Browser Javascript Parser for XML with Namespace

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:

Upvotes: 1

Views: 946

Answers (2)

Mic
Mic

Reputation: 25164

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.

Upvotes: 1

BoDiE2003
BoDiE2003

Reputation: 1359

Using a JS framework like jQuery or Prototype for this kind of ajax scripts would help. You can also do (example) $("user[name=foo]") that will select all your user tags with with name=foo. It's a solution that many users managed to do to handle elements selection by name. And $("tag[name=foo]") is crossbrowser.

Upvotes: 0

Related Questions