Show XML Data Into ASP.NET GridView

Learn how to load XML data into an ASP.NET GridView control.

Here is an example of an XML file. You can have any of your existing XML or create a new XML file. 
  1. <Employees>  
  2. <NO1>  
  3. <Name>aaa</Name>  
  4. <ZIP>333</ZIP>  
  5. <Address>aaa</Address>  
  6. <City>aa City</City>  
  7. <State>aa</State>  
  8. </NO1>  
  9. <NO2>  
  10. <Name>bbb</Name>  
  11. <ZIP>239</ZIP>  
  12. <Address>bbb</Address>  
  13. <City>bb City</City>  
  14. <State>bbb</State>  
  15. </NO2>  
  16. <NO3>  
  17. <Name>ccc</Name>  
  18. <ZIP>100</ZIP>  
  19. <Address>ccc</Address>  
  20. <City>Bcc City</City>  
  21. <State>ccc</State>  
  22. </NO3>  
  23. </Employees>  
Now, create a new Web application using Visual Studio and add two GridView control to the default WebForm. We're going to load XML into two different GridView controls based on a filter on zip code.
 
The following code loads xml file into a DataSet then creates two DataTable objects. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. public partial class _Default : System.Web.UI.Page  
  9. {  
  10. DataRow row2;  
  11. protected void Page_Load(object sender, EventArgs e)  
  12. { }  
  13. protected void Button1_Click(object sender, EventArgs e)  
  14. {  
  15. DataSet ds = new DataSet();  
  16. ds.ReadXml(Server.MapPath("~/test.xml"));  
  17. DataTable dt = new DataTable();  
  18. DataTable dt1 = new DataTable();  
  19. for (int i = 0; i < ds.Tables.Count; i++)  
  20. {  
  21. if (Convert.ToInt32(ds.Tables[i].Rows[0]["ZIP"].ToString()) > 200)  
  22. {  
  23. dt.Merge(ds.Tables[i]);  
  24. }  
  25. else  
  26. {  
  27. dt1.Merge(ds.Tables[i]);  
  28. }  
  29. }  
  30. GridView1.DataSource = dt;  
  31. GridView1.DataBind();  
  32. GridView2.DataSource = dt1;  
  33. GridView2.DataBind();  
  34. }  
  35. }  
Build and run application. 
 
Here is a detailed tutorial, ASP.NET GridView Control