Introduction
Data may exist in much form. You may have data in relational tables residing on a relational database or portable data in form of XML. Since data exist in many forms, obviously there are many ways to manipulate or access them. One of the most popular ways of sharing data is as XML.
Considering prominent presence of XML as way of data sharing, LINQ to XML got introduced in C# 3.0 to work effectively and efficiently with XML data. LINQ to XML API contains classes to work with XML. All classes of LINQ to XML are in namespace System.XML.Linq.

Objective of this article is to understand how could we work with LINQ to XML.
Linq to XML
Let us start with below image. It depicts an isomorphic relationship between XML elements and cross-ponding LINQ to XML classes.

XML Element is a fundamental XML construct. An Element has a name and optional attributes. An XML Elements can have nested Elements called Nodes also.
XML Element is represented by XElement class in LINQ to XML. It is defined in namespace System.Xml.Linq. And it inherits the class XContainer that derives from XNode. The below tasks can be performed using the XElement class:
- It can add child element.
- It can delete child element.
- It can change child element.
- It can add attributes to an element.
- It can be used to create XML tree
- It is used to serialize the content in a text form
XElement class got many overloaded constructors. You can pass XAttribute to create XML elements with attribute.
If you examine below code snippet, I am creating XML with root element Root and many child elements. Child Element Data1 and Data2 got attributes name and ID respectively with value Dj and U18949.
On executing above code you should get below output:

Let us stop here and examine how Attributes of XML is mapped in XAttribute of LINQ to XML. XML Attribute is a Name/Value pair associated with XML elements. XAttribute class represents XML Attributes in LINQ to XML. XAttribute class is overloaded with two constructors. Most frequent used constructor is one takes name and values as input parameter. In listing 1 the attributes of the element are being created using the XAttribute class.
A XML tree can be constructed using XAttribute and XElement classes.
Assume you have a list of Authors as below code listing, Author is a custom class.
XML tree can be constructed from List of Authors as below.
The above code snippet will create Authors as root element. There may be any number of Authors as child element inside root element Authors. There are two other elements Name and NumberOfArticles are in XML tree.
There may be scenario when you want to create XML tree from a SQL Server table. You need to follow below steps,
- Create Data Context class using LINQ to SQL class
- Retrieve data to parse as XML
- Create XML tree
- Create elements and attributes using XElement and XAttribute
- WCF is name of table.
By this point you know various ways of constructing XML tree and saving on file system. Now next thing come to your mind would be how to parse XML files using LINQ.
Parsing of XML document means reading XML document, identifies the function of each of the document and then makes this information available in memory for rest of the program. XElement.Parse() method is used to parse XML. This is an overloaded method. This takes a string input parameter to parse. Second overloaded method takes extra input parameter LoadOptions. LoadOptions defines where to preserve space in information or not.
Below code snippet is parsing a string with space preserve.
After knowing all the pieces of LINQ to XML, let us go ahead and find how we could put all information we have so far to bind information from XML file to DataGrid of Silverlight. It is a common requirement when you need to bind or display data from XML File to Silverlight Data Grid.
Essentially there are three steps you need to execute to bind XML to Silverlight Data Grid.
- Download content of XML file as string using WebClient class.
- Parse XML file using LINQ to XML
- Bind parsed result as item source of Data Grid.
First you need to prepare XML file as data source. Put XML file in bin folder of Silverlight project. However you can parse XML file from remote location as well.
We are going to bind Data.xml residing in client bin folder to Data Grid.
Next task you need to design XAML page. I am keeping it simple and putting a Button and DataGrid . On click event of button datagrid will be bind with data from xml file.
Xaml design would look like below code snippet.
On click event of button, make an asynchronous call and download the file.
Once the string is downloaded, you need to parse the downloaded XML.
XML can be parsed as below. On examining below code, you will find XML file is loaded using XDocument. After loading file is being traversed using Descendants method. On getting the values for each Student node, you need to create instance of Student and add it to the list of Student.
Explanation
- Function is taking string as input parameter. Here we will pass e.Result from Downloadcompletedstring event.
- Creating an instance of XDocument by parsing string
- Reading each descendants or element on Xml file and assigning value of each attribute to properties of Entity class (Student).
We need to create an Entity class to map the data from XML File. I am going to create a class Student with properties exactly as the same of attributes of Student Element in XML file.
Student class is listed as below,
On running you should get the expected output.
Assume you have data in XML file as below. This file is saved in a location on the D: drive.
Listing 1: Data.xml
To fetch all the Books, just you need to parse the XML file. Find the descendants book and fetch it in anonymous class.
If you want to fetch a particular book, you need to apply where condition while parsing XML file.
You need to fetch author Id of a particular book with Id bk102. To do that you need to select as below,
To fetch the entire author name, you need to execute below query.
I hope this article was useful. Thanks for reading.
About Dhananjay Kumar
 |
Dhananjay Kumar is a developer who blogs at http://debugmode.net/. He is Microsoft MVP ,Telerik MVP and Mindcracker MVP. You can follow him on twitter @debug_mode
This author has published 8 articles on DotNetSlackers. View other articles or the complete profile here.
|
You might also be interested in the following related blog posts
Migrated from Community Server to DasBlog
read more
Serialising Microsoft StreamInsight QueryTemplates
read more
Pie Chart Easy AS.
read more
BLinq - Linq to Bing Search APIs
read more
Telerik, Oslo and RAD Make My Application" button
read more
How To: Display Hierarchical Data with Row Details (RadGridView for Silverlight)
read more
Whats New In Silverlight 3 - Multi-Select List Box
read more
WSE, DIME; WCF, MTOM; OH My!
read more
System.Data.Linq.Binary is not XmlSerializable
read more
LINQ in Action XML samples now in LINQPad too
read more
|
|
Please login to rate or to leave a comment.