Home > Web Front-end > JS Tutorial > How Can I Parse XML Strings in JavaScript?

How Can I Parse XML Strings in JavaScript?

Patricia Arquette
Release: 2024-12-23 05:56:34
Original
889 people have browsed it

How Can I Parse XML Strings in JavaScript?

Parsing XML Strings in JavaScript

Challenge:

You're working with a variable string containing valid XML, and you need to parse it in JavaScript.

Solution:

Using the DOMParser (supported by major browsers):

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

For IE 8 and older:

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

Usage:

To parse an XML string, use parseXml to obtain a Document object. Then, you can traverse the DOM using standard methods like childNodes and getElementsByTagName().

Example:

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

Using jQuery (for jQuery 1.5 and higher):

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

The above is the detailed content of How Can I Parse XML Strings in JavaScript?. 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