Parsing XML from a variable string is a common task when working with web services or other data sources. JavaScript provides several methods for accomplishing this task, depending on the level of browser support required.
The DOMParser interface provides a cross-browser way to parse XML into a DOM Document object. This method is supported by all major browsers.
function parseXml(xmlStr) { return new window.DOMParser().parseFromString(xmlStr, "text/xml"); }
If you need to support older versions of Internet Explorer, you can use the ActiveXObject to parse XML.
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"); }
If you're using jQuery, you can use its built-in $.parseXML() method.
var xml = $.parseXML("<foo>Stuff</foo>"); alert(xml.documentElement.nodeName);<h3>Example Usage</h3> </h3> <p>Once you have an XML document, you can use standard DOM methods to navigate and access its content. For example:</p> <pre class="brush:php;toolbar:false">var xml = parseXml("<foo>Stuff</foo>"); alert(xml.documentElement.nodeName); // "foo"
The above is the detailed content of How to Parse XML from a String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!