Creating Charts from XML Data

Here is a tutorial on creating Charts using XML Data from an external source and integrating it in ASP.NET MVC Application. 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.

If you haven’t already, please refer to this tutorial for step by step instruction of adding charts to your ASP.Net MVC Application. We recommend that you download the Sample Visual Studio Project and try it on your own to understand the API better.


Download ASP.Net MVC Chart Samples

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("/home/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 fetch and parse the data to CanvasJS supported format and then pass the dataPoints to the chart.



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