Home >Web Front-end >JS Tutorial >How Can I Parse XML Data in JavaScript Using the DOM?

How Can I Parse XML Data in JavaScript Using the DOM?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 01:01:101001browse

How Can I Parse XML Data in JavaScript Using the DOM?

Parse XML using JavaScript: A Comprehensive Solution

To parse XML data in JavaScript, you can utilize the DOM (Document Object Model) without external libraries.

Parsing XML Data from a String

If the XML is stored in a variable named txt, you can parse it using the DOMParser:

if (window.DOMParser) {
  parser = new DOMParser();
  xmlDoc = parser.parseFromString(txt, "text/xml");
} else {
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(txt);
}

Retrieving Specific Values from Nodes

Once the XML is parsed, you can retrieve specific data from the nodes:

// Get house address number
streetNumber = xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

// Get street name
street = xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

// Get postal code
postalCode = xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

Handling XML with Namespace Prefixes

If the XML contains namespace prefixes, you should use the namespace URI when requesting the node:

console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue); // Gets "streetNumber" without the 'sn' prefix

console.log(xmlDoc.getElementsByTagNameNS("example.com/postal", "postalcode")[0].childNodes[0].nodeValue); // Gets postal code with 'p' namespace prefix

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