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" ?>
<Departments>
<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"/>
</Departments>
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")
where d.HasAttributes
select new
{
Name = d.Attribute("Name").Value,
Id = d.Attribute("Id").Value
};
GridView1.DataSource = data;
GridView1.DataBind();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
| Name | Id |
| HR | 1 |
| Finance | 2 |
| Software ngineering | 3 |
| Quality Assurance | 4 |
| Manufacturing | 5 |
| Sales | 6 |
So easy ! Hope this help.
Regards,
Sheo Narayan, Microsoft MVP
The Founder
http://www.dotnetfunda.com
Found interesting? Add this to: