Home >Web Front-end >JS Tutorial >How to Parse XML Files in JavaScript Across Browsers?

How to Parse XML Files in JavaScript Across Browsers?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 02:15:02893browse

How to Parse XML Files in JavaScript Across Browsers?

Cross-Browser XML Parsing in Javascript

Problem:

How can XML files be parsed in Javascript across browsers and platforms?

Solution:

The following Javascript code can be used to achieve cross-browser parsing:

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

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Live Demo:

This code works in all major browsers, including IE 6. Check out the live demo below:

[Live Demo Link]

The above is the detailed content of How to Parse XML Files in JavaScript Across 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