4

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.

4
  • Is this the actual XML your using, it appears to contain syntax errors. Commented May 20, 2009 at 19:14
  • Woops. I didnt match the XML tags. This does not matter though. The question still stands. Commented May 20, 2009 at 19:17
  • I matched the tags in the code example. Now it is more readable. Any ideas? Commented May 20, 2009 at 19:26
  • I have the answer for this now. But whenever I post it, it does not show up. Any ideas? Commented May 24, 2009 at 13:10

8 Answers 8

9

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much. These are two very good plugins which I have been trying to get to work.
If you check the plugin source, it in turn uses ActiveX object to convert xml string to xml object.
4

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.

2 Comments

Your client side example alert() produces "[null]". Fixing it by replacing $xml.find("outer") with .find("books") works in FF but produces "[]" in IE which is exactly the original problem that @Jono is reporting.
Oh ya, woops... haha; I didn't put the full XML in the string. That's too bad about the IE problem though. I wonder if he tried my JSON method. It should work as expected.
3

Put the the XML string into a Javascript variable:

var xmlString = $('<?xml version="1.0"?><Customers><Customer Name="Allan Border" Age="26" ContactNumber="004416165245" Address="Unit # 24 East London" City="London" Country="England"></Customer><Customer Name="Jennifer" Age="28" ContactNumber="004416165248" Address="Unit # 28 West London" City="London" Country="England"></Customer></Customers>');

Now you can parse the XML by iterating through each of the customer nodes:

$(xmlString).find("Customer").each(function () {
 var customerName = $(this).attr("Name");
 var age = $(this).attr("Age");
 var contactNumber = $(this).attr("ContactNumber");
 var address = $(this).attr("Address");
 var city = $(this).attr("City");
 var country = $(this).attr("Country");
 });

Comments

1

First off, the jQuery constructor takes HTML not XML... that being said, your XML may work - but it depends on a lot of browser dependent behavior. Also, you may have better success by appending the newly created elements to a hidden element on the page somewhere and then trying to query it:

var xml = "<books><book><title>Title</title></book></books>";
$(xml).appendTo("#hidden");
alert($("#hidden books").length);

1 Comment

Hmm. Your idea is having the same outcome for me. Works in FF, but not IE. Well maybe I would mention my bigger question. I have a list of things that I want to query as a database. But I want to do this all client side. Which means I cant make .ajax requests. So I am hiding the list as an XML database in the page itself. Inside a comment, inside an HTML div. Kinda weird but I cant find another way to maintain this table. Maybe I am overlooking an easier method?
1

In Javascript for Selenium reading XML file in browser:

function loadXMLFromDOM2XMLString( xmlString, xmltag, currentChildNode ) { 
var nodes = currentChildNode.childNodes; 
var i = 0 ;
var node = nodes[i];
while ( i < nodes.length) {
   if (node.data == null) {xmltag = '<'+node.localName+'>';} else {xmltag = node.data;};
   xmlString = xmlString  + xmltag;
   xmlString = loadXMLFromDOM2XMLString( xmlString, xmltag, node  );   
   if (node.data == null) {xmltag = '<'+'/'+node.localName+'>';} else {xmltag = "";};
   xmlString = xmlString + xmltag;
   i++;
   node = nodes[i];
}
 return xmlString ;
} ;
var xmlString = "";
var xmltag = "";

var currentChildNode = window.document;

xmlString = loadXMLFromDOM2XMLString( xmlString, xmltag, currentChildNode );
xmlString;

Comments

0

With string xml in ie you need to use .filter as it doesnt want to recognise the xml node tree.

Try this in ie8 with the debugger visible to get the console output.

Comments

0

So what about instead of storing the XML dataset in the DOM, convert it to an HTML table and make it invisible. That should solve the jQuery problems... at least the browser specific issues. Then back to work on refining your selectors.

4 Comments

I cannot just make an HTML table, because it is a very nested dataset. This is why I am using XML. So I just tried putting the XML in a hidden div. I want this method to work, but it does not for the following reason. I need to make sure my XML tags do not conflict with the HTML ones (ie - Title). So I do this, but then jQuery selectors will not find these tags in IE. In FF, any made up tag can be searched for. But IE seems to be restricting me to the HTML subset.
Just FYI, you could nest tables as well... anyway if I bang on a problem too long and it just isn't going anywhere or it is too complex... it usually means I am going about it the wrong way. I think you would likely be better off using JSON to serialize your structure and maybe something like google gears to persist it on the client - if that is available.
Yes. I am working on the JSON solution. I am curious what is meant by your reference to google gears.
Just that Gears can persist the data across page loads, so you don't have to send it across the wire with each request.
0

It's been a while, but I just realized that I forgot to post how I solved the problem with your combined ideas.

I needed an entirely client side database (no PHP).

I created a div with an HTML comment in it containing the XML. I parsed the HTML comment with this and then I converted the XML to JSON with this.

   var xmltext = $("#piecelist").comments();
   var json = $.xml2json(xmltext.html());

You can see my method in action here: http://wesculpt.net/art.html

Maybe I should turn this method into a jQuery plugin.

Thanks for all your help everyone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.