Home >Web Front-end >JS Tutorial >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:
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:
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!