Posted by: Zeeshan Amjad | January 4, 2011

Using LINQ to display XML data in DataGrid


When we have XML data we can use LINQ to easily parse this rather than using the traditional DOM or SAX APIs. Suppose we have the following XML data (taken from the MSDN).

 

Code Snippet
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <portfolio>
  3.   <stock>
  4.     <shares>100</shares>
  5.     <symbol>MSFT</symbol>
  6.     <price>$70.00</price>
  7.     <info>
  8.       <companyname>Microsoft Corporation</companyname>
  9.       <website>http://www.microsoft.com</website>
  10.     </info>
  11.   </stock>
  12.   <stock>
  13.     <shares>100</shares>
  14.     <symbol>AAPL</symbol>
  15.     <price>$107.00</price>
  16.     <info>
  17.       <companyname>Apple Computer, Inc.</companyname>
  18.       <website>http://www.apple.com</website>
  19.     </info>
  20.   </stock>
  21.   <stock>
  22.     <shares>100</shares>
  23.     <symbol>DELL</symbol>
  24.     <price>$50.00</price>
  25.     <info>
  26.       <companyname>Dell Corporation</companyname>
  27.       <website>http://www.dell.com</website>
  28.     </info>
  29.   </stock>
  30.   <stock>
  31.     <shares>100</shares>
  32.     <symbol>INTC</symbol>
  33.     <price>$115.00</price>
  34.     <info>
  35.       <companyname>Intel Corporation</companyname>
  36.       <website>http://www.intel.com</website>
  37.     </info>
  38.   </stock>
  39. </portfolio>

 

There are more than one way to parse this XML and load into data grid. One way is to create a class to store the information. Here is one such class.

Code Snippet
  1. public class StockInfo
  2. {
  3.     public String Shares
  4.     { get; set; }
  5.  
  6.     public String Symbol
  7.     { get; set; }
  8.  
  9.     public String Price
  10.     { get; set; }
  11.  
  12.     public String Company
  13.     { get; set; }
  14.  
  15.     public String WebSite
  16.     { get; set; }
  17. }

Now first we load the XML document using the TextReader class.Here is a class diagram of TextReader class.

 

TextReader

Here is a code to load the XML document.

Code Snippet
  1. TextReader tr = new StringReader(response);

 

Now load it into XDocument class. Here is a class diagram of LINQ.

Linq

Here is a code to load the document and then parse it using LINQ.

Code Snippet
  1. XDocument doc = XDocument.Load(tr);
  2.  
  3. var result = from c in doc.Descendants("stock")
  4.         select new StockInfo
  5.         {
  6.             Shares = c.Element("shares").Value,
  7.             Symbol = c.Element("symbol").Value,
  8.             Price = c.Element("price").Value,
  9.             Company = c.Element("info").Element("companyname").Value,
  10.             WebSite = c.Element("info").Element("website").Value
  11.         };

To load it into DataGrid we only have to convert it into List using ToList method and assign it into ItemsSource property of DataGrid. Here is a code of it.

Code Snippet
  1. grid.ItemsSource = result.ToList<StockInfo>();

 

But there is one even shortcut of this. Instead of create class of StockInfo we can use the Anonymous object. Here is a code to do this.

Code Snippet
  1. var result = (from c in doc.Descendants("stock")
  2.         select new
  3.         {
  4.             Shares = c.Element("shares").Value,
  5.             Symbol = c.Element("symbol").Value,
  6.             Price = c.Element("price").Value,
  7.             Company = c.Element("info").Element("companyname").Value,
  8.             WebSite = c.Element("info").Element("website").Value
  9.         }).ToList();
  10.  
  11. grid.ItemsSource = result;

Here is complete XML code of the program.

Code Snippet
  1. <Window x:Class="LinqXml.MainWindow"
  2.        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  3.        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  4.        Title="XML Reader" Height="350" Width="525" Loaded="Window_Loaded">
  5.     <Grid>
  6.         <DataGrid Name="grid" Margin="5"/>
  7.     </Grid>
  8. </Window>

And here is complete C# code of it.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Data;
  8. using System.Windows.Documents;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using System.Windows.Navigation;
  13. using System.Windows.Shapes;
  14. using System.IO;
  15. using System.Xml.Linq;
  16.  
  17. namespace LinqXml
  18. {
  19.     /// <summary>
  20.     /// Interaction logic for MainWindow.xaml
  21.     /// </summary>
  22.     public partial class MainWindow : Window
  23.     {
  24.         public MainWindow()
  25.         {
  26.             InitializeComponent();
  27.         }
  28.  
  29.         private void Window_Loaded(object sender, RoutedEventArgs e)
  30.         {
  31.             String response = "<portfolio>" +
  32.                                     "<stock>" +
  33.                                         "<shares>100</shares>" +
  34.                                         "<symbol>MSFT</symbol>" +
  35.                                         "<price>$70.00</price>" +
  36.                                         "<info>" +
  37.                                             "<companyname>Microsoft Corporation</companyname>" +
  38.                                             "<website>http://www.microsoft.com</website>&quot; +
  39.                                         "</info>" +
  40.                                     "</stock>" +
  41.                                     "<stock>" +
  42.                                         "<shares>100</shares>" +
  43.                                         "<symbol>AAPL</symbol>" +
  44.                                         "<price>$107.00</price>" +
  45.                                         "<info>" +
  46.                                             "<companyname>Apple Computer, Inc.</companyname>" +
  47.                                             "<website>http://www.apple.com</website>&quot; +
  48.                                         "</info>" +
  49.                                     "</stock>" +
  50.                                     "<stock>" +
  51.                                         "<shares>100</shares>" +
  52.                                         "<symbol>DELL</symbol>" +
  53.                                         "<price>$50.00</price>" +
  54.                                         "<info>" +
  55.                                             "<companyname>Dell Corporation</companyname>" +
  56.                                             "<website>http://www.dell.com</website>&quot; +
  57.                                         "</info>" +
  58.                                     "</stock>" +
  59.                                     "<stock>" +
  60.                                         "<shares>100</shares>" +
  61.                                         "<symbol>INTC</symbol>" +
  62.                                         "<price>$115.00</price>" +
  63.                                         "<info>" +
  64.                                             "<companyname>Intel Corporation</companyname>" +
  65.                                             "<website>http://www.intel.com</website>&quot; +
  66.                                         "</info>" +
  67.                                     "</stock>" +
  68.                                 "</portfolio>";
  69.  
  70.             TextReader tr = new StringReader(response);
  71.             XDocument doc = XDocument.Load(tr);
  72.  
  73.             var result = (from c in doc.Descendants("stock")
  74.                     select new
  75.                     {
  76.                         Shares = c.Element("shares").Value,
  77.                         Symbol = c.Element("symbol").Value,
  78.                         Price = c.Element("price").Value,
  79.                         Company = c.Element("info").Element("companyname").Value,
  80.                         WebSite = c.Element("info").Element("website").Value
  81.                     }).ToList();
  82.  
  83.             grid.ItemsSource = result;
  84.         }
  85.     }
  86. }

Here is the output of the program.

LinqXml

Advertisements

Responses

  1. Very well done!

  2. […] Zeeshan wrote some fantastic commentary on how to use LINQ to load data from XML to a WPF DataGrid.  Though I’ve not had the chance to test the concept, the outline looked pretty straightforward and understandable. https://zamjad.wordpress.com/2011/01/04/using-linq-to-display-xml-data-in-datagrid/#comment-456 […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: