Home > Web Front-end > JS Tutorial > body text

How to Parse XML Files in JavaScript Across Browsers?

Patricia Arquette
Release: 2024-11-12 02:15:02
Original
850 people have browsed it

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

Example usage:

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

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!

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