XML Parsing of a Variable String in JavaScript
Parsing well-formed XML strings in JavaScript is crucial for processing data in web applications. Let's explore how to accomplish this using JavaScript code.
In modern browsers, a straightforward approach is to utilize the window.DOMParser:
function parseXml(xmlStr) { return new window.DOMParser().parseFromString(xmlStr, "text/xml"); }
This function will return an XML document that can be manipulated using DOM methods.
For older browsers (including IE<=8), the following workaround using ActiveXObject can be used:
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"); }
Once an XML document is acquired, DOM navigation techniques like childNodes and getElementsByTagName() can be employed to access desired nodes.
For instance, the following usage:
var xml = parseXml("<foo>Stuff</foo>"); alert(xml.documentElement.nodeName);</p> <p>...will alert the node name "foo".</p> <p>jQuery also provides a parseXML() method that can be utilized for XML parsing.</p> <pre class="brush:php;toolbar:false">var xml = $.parseXML("<bar>Content</bar>"); alert(xml.documentElement.nodeName);
The above is the detailed content of How to Parse Variable XML Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!