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.
//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 created a basic XML string. The XML in this case represents a reminder about a meeting.
- We created a new DOMParser instance.
- 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.
- Finally, we logged the result to the browser console.
Now, let’s read the value of one of our XML elements:
//Read one of our XML elements. var date = xmlDocument.getElementsByTagName("date").childNodes.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!