Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to XML object in JavaScript?

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?

like image 785
Jack Roscoe Avatar asked Jun 16 '10 14:06

Jack Roscoe


1 Answers

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 xmlDoc = parseXml("<foo>Stuff</foo>"); if (xmlDoc) {     window.alert(xmlDoc.documentElement.nodeName); } 

Since jQuery 1.5, you can use jQuery.parseXML(), which works in exactly the same way as the above code:

var xmlDoc = jQuery.parseXML("<foo>Stuff</foo>"); if (xmlDoc) {     window.alert(xmlDoc.documentElement.nodeName); } 
like image 115
Tim Down Avatar answered Oct 19 '22 16:10

Tim Down