XML Parsing with Jquery for IE7+ and Mozilla

766 Views Asked by At

I have been working on a web application where I need to parse my xml in jquery. I am building my web app to work on IE7 to IE10 and in mozilla. I wanted to iterate to my xml so I wrote below code.

<script type='text/javascript' src="jquery/jquery-1.7.1.min.js"></script>

    <script type="text/javascript" language="javascript">
        var xml = '<root><cell id="1"> </cell><cell id="2"> </cell></root>';       
        //works in ie7
        $(xml).filter("cell").each(function () {
            alert('ie'+$(this).attr('id'));
        });
       //works in mozilla
        $(xml).find('cell').each(function () {
            alert('mozilla'+$(this).attr('id'));
        });
    </script>

But what i found is that i need to write different looping mechanism to fetch from xml for different browser. Which is kind of weird as I am using Jquery so it should be all browser compatible.

So is there a better way of reading from xml which will work in all browsers so that i dont have to write browser check code?

1

There are 1 best solutions below

0
On BEST ANSWER

Do not use jQuery's main $() function to parse XML. It attempts to parse the XML as HTML using an HTML element's built-in innerHTML property, which does not work properly but comes close enough to lull people into a false sense of security. Use parseXML() instead:

var xmlDoc = $.parseXML(xml);

$(xmlDoc).find("cell").each(function () {
    alert( $(this).attr('id') );
});