4

What is the jQuery alternative to the following JavaScript code?

var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");

I believe a jQuery alternative would be more cross-browser compatible?

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
Jack Roscoe
  • 4,293
  • 10
  • 37
  • 46
  • See http://stackoverflow.com/questions/2124924/can-xml-be-parsed-reliably-using-jquerys-responsexml-syntax and http://stackoverflow.com/questions/2908899/jquery-wont-parse-xml-with-nodes-called-option (hint: jQuery is not meant to parse xml. It's meant to *traverse* an already parsed DOM tree) – Crescent Fresh Jun 16 '10 at 15:00

3 Answers3

3

The cross-browser approach is the following, which I posted a few minutes ago in answer to a similar question:

var parseXml;

if (window.DOMParser) {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    parseXml = function() { return null; }
}

var xml = parseXml("<foo>Stuff</foo>");
if (xml) {
    window.alert(xml.documentElement.nodeName);
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Nice. Where jQuery comes in: `$(parseXml("Stuff")).find('stuff')` (i.e. this correctly uses jQuery to traverse, not parse). – Crescent Fresh Jun 16 '10 at 15:06
-1

var $parsedXml = $(xmlstring);

For exmaple, if you have something like

<object>
  <property id="prop1" value="myVal" />
</object>

as your xmlstring, you could do

var prop1 = $(xmlstring).find('#prop1').attr('value');

to get the value of the object property.

James Sumners
  • 14,485
  • 10
  • 59
  • 77
  • 2
    [This does not work well](http://stackoverflow.com/questions/2908899/jquery-wont-parse-xml-with-nodes-called-option). – SLaks Jun 16 '10 at 15:04
-1

Take a look at these plugins:

xmlDOM - http://plugins.jquery.com/project/XmlDOM
jParse - http://jparse.kylerush.net/

Luke Bennett
  • 32,786
  • 3
  • 30
  • 57