Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query an XML string via DOM in jQuery

Tags:

jquery

dom

I would like to take a string and treat it as XML. Then I will be able to query with DOM via the jQuery.find. Everything was working fine in Firefox, but I realized this is not working in IE.

I am doing this:

  var t = "<div><outer><inner>abc</inner><inner>def</inner></outer></div>";
  alert("[" + $(t).find("outer").html() + "]");

In Firefox 3 it prints:

[<inner>abc</inner><inner>def</inner>]

In IE 7 it prints:

[]

Any workarounds for getting this to work across browsers?

Thanks.

like image 271
Jono Avatar asked Dec 02 '22 08:12

Jono


2 Answers

There are a 2 ways to approach this.

  1. Convert the XML string to DOM, parse it using this plugin or follow this tutorial
  2. Convert the XML to JSON using this plugin.
like image 123
Jose Basilio Avatar answered Dec 24 '22 10:12

Jose Basilio


Would it be possible to store the XML as JSON (I would assume it would be)? For instance, in PHP, you can convert XML to an Array or Object and then convert that into JSON with json_encode. You could then echo that out as a javascript variable like so:

In PHP:

<?php
$xml = "<div><outer><inner>abc</inner><inner>def</inner></outer></div>";
$xml_object = simplexml_load_string(xml);
$json = json_encode($xml_object);
?>
<script language="javascript">
$(function() {
    // eval() is okay to use if you know where the JSON is 
    // coming from (and, of course, you do...) 
    var data = eval('<?php echo $json; ?>');
    $(document).data('myapp.data',data);
});
</script>

And now, whenever you need to access that data, you can just get it like so:

function some_function() {
    var data = $(document).data('myapp.data');
    $.each(data.div.outer,function() {
        // Would alert 'abc' then 'def'
        alert(this.inner);
    });
}

I hope all that makes sense. At least you won't have to worry about XML anymore on the client side. Of course, if you absolutely need to, I've found that this has worked for me in the past:

var xml = "<div><outer><inner>abc</inner><inner>def</inner></outer></div>";
var $xml = $('<div />').append(xml);
alert("[" + $xml.find("outer").html() + "]");

Edit I modified my code to use the actual XML you provide--not sure where I mixed up there (must've grabbed the snippet from someone else's answer on accident). You should really give my first suggestion a shot--it should work.

like image 37
KyleFarris Avatar answered Dec 24 '22 12:12

KyleFarris