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:

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

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;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

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


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt
txt = `
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>
  <s:street>Roble Ave</s:street>
  <sn:streetNumber>649</sn:streetNumber>
  <p:postalcode>94025</p:postalcode>
</address>`;

//Everything else the same
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);
}

//The prefix should not be included when you request the xml namespace
//Gets "streetNumber" (note there is no prefix of "sn"
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);

//Gets Street name
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);

//Gets Postal Code
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);

Answer from Enigmadan on Stack Overflow
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › XML › Guides › Parsing_and_serializing_XML
Parsing and serializing XML - MDN Web Docs
js · const xmlStr = '<q id="a"><span id="b">hey!</span></q>'; const parser = new DOMParser(); const doc = parser.parseFromString(xmlStr, "application/xml"); // print the name of the root element or error message const errorNode = doc.querySelector("parsererror"); if (errorNode) { console.log("error while parsing"); } else { console.log(doc.documentElement.nodeName); } Here is sample code that reads and parses a URL-addressable XML file into a DOM tree: js ·
Top answer
1 of 2
214

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:

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

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;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

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


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt
txt = `
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>
  <s:street>Roble Ave</s:street>
  <sn:streetNumber>649</sn:streetNumber>
  <p:postalcode>94025</p:postalcode>
</address>`;

//Everything else the same
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);
}

//The prefix should not be included when you request the xml namespace
//Gets "streetNumber" (note there is no prefix of "sn"
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);

//Gets Street name
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);

//Gets Postal Code
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);

2 of 2
17

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have 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");
}

Example usage:

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

Which I got from https://stackoverflow.com/a/8412989/1232175.

People also ask

Can JavaScript parse XML attributes and elements differently?
Yes, tools like fast-xml-parser let you choose how to handle attributes separately from elements using options.
🌐
iproyal.com
iproyal.com › blog › javascript-parse-xml
How to Parse XML in JavaScript (With Examples)
How do I handle XML namespaces in JavaScript?
Use an XML parser that supports namespaces. fast-xml-parser has specific settings for that, but DOM-based parsers are generally more convenient for that.
🌐
iproyal.com
iproyal.com › blog › javascript-parse-xml
How to Parse XML in JavaScript (With Examples)
How do I preserve the order of XML tags when parsing?
Most parsers keep the order by default. Check parser settings to be sure.
🌐
iproyal.com
iproyal.com › blog › javascript-parse-xml
How to Parse XML in JavaScript (With Examples)
🌐
npm
npmjs.com › package › fast-xml-parser
fast-xml-parser - npm
2 weeks ago - Validate XML, Parse XML to JS Object, or Build XML from JS Object without C/C++ based libraries and no callback.
      » npm install fast-xml-parser
    
Published   Mar 23, 2026
Version   5.5.9
Author   Amit Gupta
🌐
W3Schools
w3schools.com › xml › xml_parser.asp
XML Parser
The XMLHttpRequest Object has a built in XML Parser.
🌐
Apify
blog.apify.com › javascript-parse-xml
How to parse XML in JavaScript (step-by-step guide)
December 7, 2025 - Learn how to parse XML with JavaScript using methods like DOMParser, xml2js, and streams. Explore techniques for handling large files and writing XML data. ... Share this article: Copied! JSON is the go-to format for most web applications today, but XML (Extensible Markup Language) is still ...
🌐
jQuery
api.jquery.com › jQuery.parseXML
jQuery.parseXML() | jQuery API Documentation
jQuery.parseXML uses the native parsing function of the browser to create a valid XML Document.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-parse-xml-in-javascript
How to Parse XML in JavaScript? - GeeksforGeeks
July 27, 2025 - In this approach, we are using the DOM Parser, which is built into browsers, to parse XML data.
🌐
ReqBin
reqbin.com › code › javascript › h6wipkyl › javascript-parse-xml-example
How to Parse XML in JavaScript?
September 1, 2023 - To parse XML in JavaScript, you can use DOMParser API, which converts XML strings into a structured Document Object Model (DOM). The DOM model enables easy traversal and manipulation of XML data.
🌐
iProyal
iproyal.com › blog › javascript-parse-xml
How to Parse XML in JavaScript (With Examples)
October 14, 2025 - Use fast-xml-parser when you need speed and clean output. It handles large XML strings efficiently. However, for true streaming, you may want to consider a library like SAX. If you want to work with the DOM tree in Node.js, use xmldom or @rgrove/parse-xml.
🌐
GitHub
github.com › rgrove › parse-xml
GitHub - rgrove/parse-xml: A fast, safe, compliant XML parser for Node.js and browsers. · GitHub
Mostly conforms to XML 1.0 (Fifth Edition) as a non-validating parser (see below for details). Passes all relevant tests in the XML Conformance Test Suite. Written in TypeScript and compiled to ES2020 JavaScript for Node.js and ES2017 JavaScript for browsers.
Starred by 316 users
Forked by 16 users
Languages   JavaScript 56.3% | TypeScript 43.6% | HTML 0.1%
🌐
Stwrt
andrew.stwrt.ca › posts › js-xml-parsing
Parsing XML with JavaScript · Andrew Stewart
} } }); // => "hello!" function flatten(object) { var check = _.isPlainObject(object) && _.size(object) === 1; return check ? flatten(_.values(object)[0]) : object; } function parse(xml) { var data = {}; var isText = xml.nodeType === 3, isElement = xml.nodeType === 1, body = xml.textContent && xml.textContent.trim(), hasChildren = xml.children && xml.children.length, hasAttributes = xml.attributes && xml.attributes.length; // if it's text just return it if (isText) { return xml.nodeValue.trim(); } // if it doesn't have any children or attributes, just return the contents if (!hasChildren && !h
🌐
Geshan
geshan.com.np › blog › 2022 › 11 › nodejs-xml-parser
A beginner’s guide to parse and create XML with Node.js
November 27, 2022 - In this tutorial, learn how validate and parse XML with Node.js. You will also know about creating a XML file with Node.js
🌐
CodeSignal
codesignal.com › learn › courses › hierarchical-and-structured-data-formats-1 › lessons › working-with-xml-in-javascript-using-xml2js
Working with XML in JavaScript using xml2js
When xml2js parses XML into a JavaScript object, it converts elements into properties of the object, handling attributes and child elements efficiently. Attributes of an XML element are represented as a separate property named "$" within the object.
🌐
C# Corner
c-sharpcorner.com › blogs › xml-parser-in-javascript
XML Parser In JavaScript
March 21, 2023 - XMLSerialzer() object is used to parse the XML to string using the serializeToString method.
🌐
Reddit
reddit.com › r/node › how to parse large xml file (2–3gb) in node.js within a few seconds?
r/node on Reddit: How to parse large XML file (2–3GB) in Node.js within a few seconds?
July 25, 2025 -

I have a large XML file (around 2–3 GB) and I want to parse it within a few seconds using Node.js. I tried packages like xml-flow and xml-stream, but they take 20–30 minutes to finish.

Is there any faster way to do this in Node.js or should I use a different language/tool?

context:

I'm building a job distribution system. During client onboarding, we ask clients to provide a feed URL (usually a .xml or .xml.gz file) containing millions of <job> nodes — sometimes the file is 2–3 GB or more.

I don't want to fully process or store the feed at this stage. Instead, we just need to:

  1. Count the number of <job> nodes

  2. Extract all unique field names used inside the <job> nodes

  3. Display this info in real-time to help map client fields to our internal DB structure

This should ideally happen in a few seconds, not minutes. But even with streaming parsers like xml-flow or sax, the analysis is taking 20–30 minutes.

I stream the file using gzip decompression (zlib) and process it as it downloads. so I'm not waiting for the full download. The actual slowdown is from traversing millions of nodes, especially when different job entries have different or optional fields.

🌐
o7planning
o7planning.org › 12337 › parsing-xml-in-javascript-with-domparser
Parsing XML in Javascript with DOMParser | o7planning.org
DOMParser will parse a XML into a DOM tree (like the following illustration). You need to use the APIs provided by DOM model to take necessary data. ... <!DOCTYPE html> <html> <head> <title>DOMParser Example</title> <meta charset="UTF-8"> <script src="domparser-example.js"></script> </head> ...
🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript tutorial › xml parsing in javascript
XML Parsing in JavaScript | Introduction, Types and Features
April 17, 2023 - XML parsing in JavaScript is defined as it is one kind of package or library of the software which provides an interface for the client applications to work with an XML document and it is used in JavaScript to transform the XML document into ...
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
npm
npmjs.com › package › xml2js
xml2js - npm
Ever had the urge to parse XML? And wanted to access the data in some sane, easy way? Don't want to compile a C parser, for whatever reason? Then xml2js is what you're looking for! Simple XML to JavaScript object converter. It supports bi-directional conversion. Uses sax-js and xmlbuilder-js.
      » npm install xml2js
    
Published   Jul 26, 2023
Version   0.6.2
Author   Marek Kubica
🌐
npm
npmjs.com › package › xml-parse
xml-parse - npm
November 6, 2019 - Parse XML, HTML and more with a very tolerant XML parser and convert it into a DOM.
      » npm install xml-parse
    
Published   Nov 06, 2019
Version   0.4.0
Author   Maurice Conrad
🌐
Itpscan
itpscan.ca › blog › javascript › parsing_xml.php
Using Javascript to parse XML strings - itps Home Page
The XML parser converts an XML document into an XML DOM object - which can then be manipulated with JavaScript using the same vocabulary as HTML.