How do you parse XML in JavaScript?

Back in January, we looked at how to use Vue and Axios to read from the JSON API for this blog.  I figured that it is about time to look at how to do the same thing with XML.

See the Pen
Parse XML in JavaScript – Part 1
by Joe Steinbring (@steinbring)
on CodePen.

In the above example, we are making a get request to the XML feed URL for the blog and copying the result to the this.data variable.  Unfortunately, it then throws a “No ‘Access-Control-Allow-Origin’ header is present on the requested resource.” error.  We could fix this by tweaking the settings on the server but there is another way.  Recently, I came across a project called CORS Anywhere that acts as a reverse proxy and adds CORS headers to the proxied request.  So, let’s see what it looks like with CORS Anywhere proxying the request.

See the Pen
Parse XML in JavaScript – Part 2
by Joe Steinbring (@steinbring)
on CodePen.

Right now, we are just getting the XML content and dumping it onto the page.  So, now how do we get the values out?

See the Pen
Parse XML in JavaScript – Part 3
by Joe Steinbring (@steinbring)
on CodePen.

Grabbing values out of this is more difficult than with JSON but thanks to getElementsByTagName(), it’s not too bad.

You will notice that I previously wrote about doing this in AngularJS and in pure JavaScript.  Both examples depended on getting around CORS using YQL, which isn’t around anymore.  This example still has an external dependency but since you can spin up your own heroku machine to handle it, I feel a little better about it.

 

[ Cover photo by Jeremy Bishop on Unsplash ]

Leave a Reply

Your email address will not be published. Required fields are marked *