Home > Web Front-end > JS Tutorial > How to Parse Variable XML Strings in JavaScript?

How to Parse Variable XML Strings in JavaScript?

Patricia Arquette
Release: 2024-12-10 07:03:12
Original
686 people have browsed it

How to Parse Variable XML Strings in JavaScript?

XML Parsing of a Variable String in JavaScript

Parsing well-formed XML strings in JavaScript is crucial for processing data in web applications. Let's explore how to accomplish this using JavaScript code.

In modern browsers, a straightforward approach is to utilize the window.DOMParser:

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

This function will return an XML document that can be manipulated using DOM methods.

For older browsers (including IE<=8), the following workaround using ActiveXObject can be used:

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 an XML document is acquired, DOM navigation techniques like childNodes and getElementsByTagName() can be employed to access desired nodes.

For instance, the following usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);</p>
<p>...will alert the node name "foo".</p>
<p>jQuery also provides a parseXML() method that can be utilized for XML parsing.</p>
<pre class="brush:php;toolbar:false">var xml = $.parseXML("<bar>Content</bar>");
alert(xml.documentElement.nodeName);
Copy after login

The above is the detailed content of How to Parse Variable 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