Home >Web Front-end >JS Tutorial >How Can I Parse XML Strings from Variables in JavaScript Across Different Browsers?

How Can I Parse XML Strings from Variables in JavaScript Across Different Browsers?

Susan Sarandon
Susan SarandonOriginal
2024-12-12 18:19:131075browse

How Can I Parse XML Strings from Variables in JavaScript Across Different Browsers?

XML Parsing for Variable Strings in JavaScript

Parsing XML from a variable string presents a challenge in JavaScript. This article will address this need and provide browser-compatible solutions.

Solution

In modern browsers, the recommended approach is to utilize the DOMParser() interface. The following snippet effectively parses XML strings:

function parseXml(xmlStr) {
   return new window.DOMParser().parseFromString(xmlStr, "text/xml");
}

However, for browsers that may not support DOMParser (e.g., IE <= 8), a fallback solution leveraging ActiveXObject is provided:

var parseXml;

if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return new window.DOMParser().parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &amp;&amp;
       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 the XML document is obtained, you can navigate it using standard DOM methods such as childNodes and getElementsByTagName().

jQuery Solution

jQuery, starting from version 1.5, provides a convenient parseXML() method that serves the same purpose as the above code snippets:

var xml = $.parseXML("Stuff");
alert(xml.documentElement.nodeName);

The above is the detailed content of How Can I Parse XML Strings from Variables in JavaScript Across Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn