views:

110

answers:

2

Hi,

I am aware of this question already existing, but it has given me no luck.

I have an application which loads a physicial XML document via the following method:

      jQuery.ajax( {
    type: "GET",
    url: fileName,
    dataType: "xml",
    success: function(data) {
      etc...

I parse the XML and convert it into a string which is saved into a variable so that it can easily be stored in a database. How can I now convert the data in this variable back into an XML object so that it can be parsed as such?

A: 

If it's still in XML format you should be able to just wrap it in the jQuery function and start using jQuery to parse through it. For example:

$(xmlStringFromDB).find('foo');
patrickmcgraw
+4  A: 

Non-jQuery version:

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
+1 It's not just non-jQuery, this actually parses XML properly, unlike the jQuery parser.
Anurag
I was actually looking for a jQuery solution, although I know I did not specify. I found your answer very useful though, had not considered this method before.
Jack Roscoe