Saturday, 4 May 2013

Xml To Dictionary..

XML :-

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee EmpId="1'" Name="Pankaj" />
  <Employee EmpId="2" Name="Deepanshu"/>
  <Employee EmpId="3" Name="Akash"/>
  <Employee EmpId="4" Name="Ajay"/>
  <Employee EmpId="5" Name="Dinesh"/>
  <Employee EmpId="6" Name="Rahul"/>
  <Employee EmpId="7" Name="Deepak"/>
</Employees>


C# Code :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace XMLToDict
{
    class Program
    {
static void Main(string[] args)
{
    XElement xelement = XElement.Load("..\\..\\Employees.xml");

    var empDict = (from element in xelement.Descendants("Employee")
                      let name = (string)element.Attribute("Name")
                      orderby name                   
                      select new
                      {
                          EmployeeID = element.Attribute("EmpId").Value,
                          EmployeeName = name
                      })
           .ToDictionary(a => a.EmployeeID,
                         a => a.EmployeeName);

    Console.ReadLine();

}
    }
}