Parse an XML string using JavaScript.

In this tutorial, I will show you how to parse an XML string using JavaScript. In the code examples below, we will take a string containing XML and parse it into an XMLDocument object. Converting it into an XMLDocument object allows us to easily read and manipulate the XML.

Take a look at the following JavaScript example:

//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
console.log(xmlDocument);

In the code above, we:

  1. Created a basic XML file. The XML in this case represents a reminder.
  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 mimeType to text/xml.
  4. Finally, we logged our new XMLDocument instance to the browser console.

If you run the JavaScript above and view your developer console, you should see something similar to this:

parse xml javascript

Perfect!

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!

Facebook Comments