Parse XML with JavaScript
Parsing XML involves converting XML data into a format that can be processed by JavaScript code. To do this without external frameworks like jQuery, the DOM (Document Object Model) can be utilized.
If the XML is stored in a string variable named txt, its structure could resemble the following:
<address> <street>Roble Ave</street> <mtfcc>S1400</mtfcc> <streetNumber>649</streetNumber> <lat>37.45127</lat> <lng>-122.18032</lng> <distance>0.04</distance> <postalcode>94025</postalcode> <placename>Menlo Park</placename> <adminCode2>081</adminCode2> <adminName2>San Mateo</adminName2> <adminCode1>CA</adminCode1> <adminName1>California</adminName1> <countryCode>US</countryCode> </address>
To parse this XML, follow these steps:
// Create a new DOM parser var parser = new DOMParser(); // Parse the XML string into a DOM object var xmlDoc = parser.parseFromString(txt, "text/xml");
With the DOM object available, specific XML elements can be accessed and their values retrieved:
// Get the street number var streetNumber = xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue; // Get the street name var street = xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue; // Get the postal code var postalcode = xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;
XML with namespace prefixes can also be parsed using this method, provided that the browser supports namespace prefixes. The namespace prefixes can be accessed without the prefix in the JavaScript code.
The above is the detailed content of How Can I Parse XML Data in JavaScript Without Using External Libraries?. For more information, please follow other related articles on the PHP Chinese website!