How to parse an XML string using JavaScript.

In this tutorial, we are going to show you how to parse an XML string using JavaScript.

In the example below, we will take an XML string and then parse it into an XMLDocument object.

Converting it into an XMLDocument object is very useful, as it allows us to easily read and manipulate the XML.

Reading XML with JavaScript.

Take a look at the following JavaScript code:

//A simple XML string.
var xmlString = '<reminder><date>2020-08-01T09:00:00</date><heading>Meeting</heading><body>Meeting with Mark at 10AM!</body></reminder>';

//Create a new DOMParser object.
var domParser = new DOMParser();

//Parse the XML string into an XMLDocument object using
//the DOMParser.parseFromString() method.
var xmlDocument = domParser.parseFromString(xmlString, "text/xml");

//Log it to the console

In the code above:

  1. We created a basic XML string. The XML in this case represents a reminder about a meeting.
  2. We created a new DOMParser instance.
  3. Using the DOMParser.parseFromString() method, we parsed our XML string into an XMLDocument object. We did this by setting the second parameter to text/xml.
  4. Finally, we logged the result to the browser console.

If you run the JavaScript above, you will see the following in your console:

parse xml javascript


Now, let’s read the value of one of our XML elements:

//Read one of our XML elements.
var date = xmlDocument.getElementsByTagName("date")[0].childNodes[0].nodeValue;
alert('Date for this reminder is: ' + date);

If you run the code above, your browser should display an alert saying: “Date for this reminder is: 2020-08-01T09:00:00”

Hopefully, you found this guide useful!