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

How Can I Parse XML Strings in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 05:56:34891browse

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

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

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

Using jQuery (for jQuery 1.5 and higher):

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

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!

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