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!