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
Release: 2024-12-12 18:19:13
Original
1002 people have browsed it

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");
}
Copy after login

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");
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template