Blog author: SheoNarayan
| Posted on: 4/9/2011 | Category: LINQ Blogs
| Views: 3623 | Status: [Microsoft_MVP] [Administrator]
| Points: 75
| Alert Moderator
In this small blog post I am going to show how to read attribute based XML File and store into the collection object.
My xml file (XmlData.xml) looks like below
<?xml version="1.0" encoding="utf-8" ?>
<Department Name="HR" Id="1"/>
<Department Name="Finance" Id="2"/>
<Department Name="Software Engineering" Id="3"/>
<Department Name="Quality Assurance" Id="4"/>
<Department Name="Manufacturing" Id="5"/>
<Department Name="Sales" Id="6"/>
GridView in which data shall be populated
<asp:GridView ID="GridView1" runat="server" EnableViewState="false" />
Code behind to read the attribute based XML file (XmlData.xml file). Notice that you will need to use System.Xml.Linq
namespace to work with following code snippet.
string xmlFile = Server.MapPath("~/XmlData.xml");
XDocument doc = XDocument.Load(xmlFile);
var data = from d in doc.Descendants("Department")
Name = d.Attribute("Name").Value,
Id = d.Attribute("Id").Value
GridView1.DataSource = data;
Notice that if your XML has attribute, they will not be by default converted as columns or properties by LINQ so you need to explicitly retrieve the attributes and set as virtual property names of the returned object (notice the Select block into the LINQ statement).
The output of would look something like
|Software ngineering||3 |
|Quality Assurance||4 |
So easy ! Hope this help.
Sheo Narayan, Microsoft MVP
Found interesting? Add this to: