Home > Web Front-end > JS Tutorial > How to Parse XML from a String in JavaScript?

How to Parse XML from a String in JavaScript?

Barbara Streisand
Release: 2024-12-29 12:24:14
Original
359 people have browsed it

How to Parse XML from a String in JavaScript?

Parsing XML from a Variable String in JavaScript

Parsing XML from a variable string is a common task when working with web services or other data sources. JavaScript provides several methods for accomplishing this task, depending on the level of browser support required.

Using the DOMParser

The DOMParser interface provides a cross-browser way to parse XML into a DOM Document object. This method is supported by all major browsers.

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

Using ActiveXObject (for IE <= 8)

If you need to support older versions of Internet Explorer, you can use the ActiveXObject to parse XML.

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

Using jQuery

If you're using jQuery, you can use its built-in $.parseXML() method.

var xml = $.parseXML("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);<h3>Example Usage</h3>
</h3>
<p>Once you have an XML document, you can use standard DOM methods to navigate and access its content. For example:</p>
<pre class="brush:php;toolbar:false">var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName); // "foo"
Copy after login

The above is the detailed content of How to Parse XML from a String 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