user2574350 user2574350 - 3 months ago 36
Javascript Question

Parse XML using JavaScript

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

I have looked at this, XML > jQuery reading.


I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

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

 <street>Roble Ave</street>
  <placename>Menlo Park</placename>
  <adminName2>San Mateo</adminName2>

Then you can parse the XML with Javascript DOM like this:

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

And get specific values from the nodes like this:

//Gets house address number

//Gets Street name

//Gets Postal Code