Creating Charts from XML Data

Here is a turtorial on creating Charts using XML Data from an external source. Generally it’s a good idea to fetch data via ajax rather than embedding in the web page. XML data is easy to parse and generate the chart accordingly.

We will be using following XML format in this example:

<?xml version="1.0"?>
<data>
	<point>
		<x>5</x>
		<y>8</y>
	</point>
	<point>
		<x>6</x>
		<y>7</y>
	</point>
	<point>
		<x>7</x>
		<y>10</y>
	</point>
	<point>
		<x>8</x>
		<y>15</y>
	</point>
	<point>
		<x>9</x>
		<y>16</y>
	</point>
	<point>
		<x>10</x>
		<y>21</y>
	</point>
	<point>
		<x>11</x>
		<y>22</y>
	</point>
	<point>
		<x>12</x>
		<y>26</y>
	</point>
	<point>
		<x>13</x>
		<y>29</y>
	</point>
	<point>
		<x>14</x>
		<y>27</y>
	</point>
</data>

Here is the code for creating Charts using XML Data. We will get and parse the XML Data using jQuery and convert the data to CanvasJS supported format (Please refer to Working with Data). Then we will initialize a chart and pass the dataPoints to the chart.

var dataPoints = [];

$.get("https://canvasjs.com/services/data/datapoints.php?xstart=5&ystart=10&length=10&type=xml", function(data) {
	$(data).find("point").each(function () {
		var $dataPoint = $(this);
		var x = $dataPoint.find("x").text();
		var y = $dataPoint.find("y").text();
		dataPoints.push({x: parseFloat(x), y: parseFloat(y)});
	});
		
	var chart = new CanvasJS.Chart("chartContainer", {
		title: {
		    text: "Chart Using XML Data",
		},
		data: [{
		     type: "column",
		     dataPoints: dataPoints,
		  }]
	});
	
	chart.render();

});

Finalising

To summarize, in order to create a charts using XML Data, we just need to parse the data to CanvasJS supported format and then pass the dataPoints to the chart.

Below is the compilation of final code.

Try it Yourself by Editing the Code below.


If you have any questions, please feel free to ask in our forums.Ask Question