Saturday, December 11, 2010

Parsing XML using linq with c# 3.5

In this post i will include the c# (linq) code necessary to read an xml file containing definition of a list of device Ids and descriptions.
input:  String localDirectory pointing to the location of xml file to be read and parsed.
output:  ArrayList of devices parsed from the XML file.

Note: a device can be any object you want.

  
 mkrs1000
 rs1000 with output
  
  
  
 rs1100
 rs1100 demo
  



// code converting xml file to arrarylist of devices
XDocument document = XDocument.Load(localDirectory);

List<device> listOfDevices = document
   .Descendants("device")
   .Select(device => new Device
   {
       DeviceID = device.Element("deviceId").Value,
       DeviceDescription = device.Element("deviceDesc").Value
   })
   .ToList();


foreach (Device device in listOfDevices)
{
 string s = String.Format("ID: {0,-20} : Desc = {1}", device.DeviceID, device.DeviceDescription);
 Console.WriteLine(s);

}

// class representing an xml node (can be any object you want)
class Device
{
    public string DeviceID { get; set; }
    public string DeviceDescription { get; set; }
}