Problem: Working with XML data often involves retrieving it as a string from dynamic sources. How can we effectively parse and manipulate this XML data using JavaScript code that is compatible with modern browsers?
Solution:
For browsers supporting the DOMParser interface, the following function provides a simple XML parsing mechanism:
function parseXml(xmlStr) { return new window.DOMParser().parseFromString(xmlStr, "text/xml"); }
Example usage:
var xml = parseXml('<foo>Stuff</foo>'); console.log(xml.documentElement.nodeName); // Outputs: "foo"
In cases where DOMParser is unavailable, such as in Internet Explorer versions up to 8, the following code snippet provides a fallback using ActiveXObject:
var parseXml; if (typeof window.DOMParser != "undefined") { 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 { throw new Error("No XML parser found"); }
jQuery versions 1.5 and later include a convenient $.parseXML() method that offers similar functionality:
var xml = $.parseXML('<foo>Stuff</foo>'); console.log(xml.documentElement.nodeName); // Outputs: "foo"
The above is the detailed content of How Can I Parse Dynamic XML Strings in JavaScript Using Modern and Legacy Browser Compatible Methods?. For more information, please follow other related articles on the PHP Chinese website!