Quick demo of accessing XML data with jQuery

This post is more than 2 years old.

This blog post is mainly for my own memory - but a user asked about access CDATA values stored in an XML field via JavaScript. I'm using jQuery to work with XML and wrote up a very quick demo. For the most part, it seems like it "just works", but I assume there are going to be some edge cases. I'll update the demo to add more examples if folks would like.

First, I created an XML sample and named it data.xml:

<?xml version="1.0" encoding="UTF-8" ?> <root> <name>Raymond</name> <bio> <![CDATA[ Willy nilly stuff with <b>some html</b> and crap in it. ]]> </bio> <likes> <like>Star Wars</like> <like>Beer</like> <like>Cookies</like> </likes> <skillshot range="10">rifle</skillshot> </root>

Notice I've got a simple value, a value with CDATA, an collection of items, and one item with an attribute too. Here's the jQuery side:

<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" />

&lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;

&lt;script type="text/javascript"&gt;

$(function() {

		$.get("data.xml", {}, function(res) {

			var name = $(res).find("name");
			console.log("name = "+name.text());

			var bio = $(res).find("bio");
			console.log("bio = "+bio.text());

			//notice I ask for the child like tag, not the parent likes
			var likes = $(res).find("like");
			$(likes).each(function(idx,item) {
				console.log("like # "+idx+" = "+$(item).text());

			var sshot = $(res).find("skillshot");
			console.log("skillshot = "+sshot.text());
			console.log("skillshot = "+sshot.attr("range"));

		}, "xml");


</head> <body>

</body> </html>

Stepping through this - notice first that I tipped off jQuery to the data type. I probably didn't need this, but i like being explicit. jQuery automatically converts the result text into a proper XML object. Once I have that, then I can use the find function to grab my nodes. At this point, it almost acts like any other regular DOM item. Notice how I can simply use .text on both name and bio. It just works.

The array of items is a bit different. I grab them all and then iterate over it.

And finally - look how I handle the skillshot item. I can still do .text to get the text value, but I can also use .attr (again, like a regular DOM item) to get the attribute.

Hope this is helpful to folks. If you want to run this, hit the demo link below and ensure your console is open.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com