Home >Web Front-end >JS Tutorial >How Can I Parse XML Documents Using JavaScript\'s DOM API?

How Can I Parse XML Documents Using JavaScript\'s DOM API?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 03:11:111033browse

How Can I Parse XML Documents Using JavaScript's DOM API?

Parse XML Using JavaScript

Parsing XML documents in JavaScript is a common requirement for web development. This can be easily achieved using the native JavaScript DOM (Document Object Model) API.

The DOM API

The DOM API provides a hierarchical representation of an XML document, allowing developers to access and manipulate XML nodes and their attributes. To parse an XML document using the DOM API, follow these steps:

  1. Create a DOMParser object: This object is used to parse XML strings into a DOM structure.
  2. Parse the XML string: Call the parseFromString method of the DOMParser object to parse the XML string and create a DOM document.
  3. Access XML nodes: Use methods such as getElementsByTagName and getElementsByTagNameNS to access the desired XML nodes based on their tag names and namespaces (if applicable).

Example

Consider the following XML string:

<address>
  <street>Roble Ave</street>
  <streetNumber>649</streetNumber>
  <postalcode>94025</postalcode>
</address>

To parse this XML string and access the street name, street number, and postal code, use the following JavaScript code:

const txt = `<xml string here>`;

if (window.DOMParser) {
  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(txt, "text/xml");
  console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue); // Logs "Roble Ave"
  console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue); // Logs "649"
  console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue); // Logs "94025"
} else {
  // Code for older browsers using ActiveXObject
}

Note:

  • Namespace Prefixes: If the XML document contains namespace prefixes, be sure to specify the namespace when accessing XML nodes using getElementsByTagNameNS.
  • Browser Support: The DOM API is supported by all major browsers.

The above is the detailed content of How Can I Parse XML Documents Using JavaScript\'s DOM API?. 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