views:

77

answers:

2

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"&gt;
   <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
A: 

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.

BoDiE2003
jQuery and Prototype are in my "never use" category. I'll adopt them when they are *native* to all browsers. They have too many problems. -- also, as far as I'm aware they don't handle namespaces, which is really what the question is about.
vol7ron
A: 

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.

Mic
I actually am creating the XML server-side, so I would guess that I'd start out with JSON instead of needing to convert it. I'm using the XML as part of some web-authentication. Since I have control over the input, I could easily just return delimited ASCII w/o any markup, but I really haven't had the need to use the XML Dom in some time, so this is a new project :)
vol7ron
I did XML/XSLT based web apps for 10+ years. When I moved to JSON it was a liberation and I wouldn't come back for nothing. ASCII messaging is not ideal, as it generally breaks your code when you change the message, while XML and JSON, as long as you add stuff, the old code continue to work as expected.
Mic