Link to home
Start Free TrialLog in
Avatar of wayside
wayside

asked on

xml DOM difference between IE and Firefox

Say I have an XML string that looks something like this:

<users>
   <user>
     <option value="foo">bar</option>
     <option value="foo2">bar2</option>
   </user>
   <user2>
     <option value="foo">bar</option>
     <option value="foo2">bar2</option>
  </user2>
</users>

I can load this into an XML doc on IE like this:

    txt = ... // xml string
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);

On Firefox, like this:

    var parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "application/xml");

So far, everything is good.

When I want to extract parts of the document, on IE I can do this:

xmlObjs = xmlDoc.getElementsByTagName("user/option");

This gives me a collection of the two options under user.

However, it does not work on Firefox - I get nothing.

I can do this:

xmlObjs = xmlDoc.getElementsByTagName("option");

but this gives me 4 nodes - two under user, and two under user2.

I could do this:

xmlObjs = xmlDoc.getElementsByTagName("user");

and walk the children looking for those nodes with a value of "option", but this takes a lot more code.

How do I do

xmlObjs = xmlDoc.getElementsByTagName("user/option");

in Firefox? I am converting a large web app to be able to run on both IE and Firefox, and the above line is in many places, I'm trying to minimize the changes I have to make.

Thanks.



SOLUTION
Avatar of alien109
alien109
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
PS: You might try using sarissa (http://dev.abiss.gr/sarissa/) which does tend to hide a lot of differences and allows you to use XPATH expressions. In fact the getElementsByTagName does have the performance detriment of scanning the entire document, the direct approach /result/user/options, for example, would give you a node list overwich you could iterate.
@BigRat - that is correct, and thanks for the extra info. Helpful to me too!

wayside, another option if you can, is to use jQuery (www.jquery.com). Not only will it simplify your loading of the XML, but it gives you a lot more options for traversing and selecting nodes in your XML object.

For example, with jQuery, you can do the following - which will give you exactly what you want:

var options = $("user>option");

Hope that helps.
Avatar of wayside
wayside

ASKER

Thanks for the responses, they've been helpful.

Unfortunately using anything open-source opens up a huge can of worms, so it is not really an option.