XML parsing using JavaScript

I need to be able to parse XML using JavaScript. XML will be in a variable. I would prefer not to use jQuery or other frameworks.

I looked at this, XML> reading jQuery .

+61
javascript xml domparser
Jul 11 '13 at 21:45
source share
2 answers

I guess from your last question , I asked 20 minutes before that you were trying to parse (read and convert) the XML found using GeoNames' FindNearestAddress.

If your XML is in a string variable named txt and looks like this:

 <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> 

You can then parse the XML using the Javascript DOM as follows:

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

And get specific values ​​from these nodes:

 //Gets house address number xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue; //Gets Street name xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue; //Gets Postal Code xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue; 

Jsfiddle

+120
Jul 11 '13 at 22:04 on
source share

Next, the XML string in the XML document will be analyzed in all major browsers, including Internet Explorer 6. After that, you can use the usual DOM traversal methods / properties, such as childNodes and getElementsByTagName (), to get the nodes you want.

 var parseXml; if (typeof window.DOMParser != "undefined") { parseXml = function(xmlStr) { return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml"); }; } else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) { parseXml = function(xmlStr) { var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xmlStr); return xmlDoc; }; } else { throw new Error("No XML parser found"); } 

Usage example:

 var xml = parseXml("<foo>Stuff</foo>"); alert(xml.documentElement.nodeName); 

What did I get from https://stackoverflow.com/a/34578/ ...

+11
Jul 11 '13 at 21:59
source share



All Articles