Saturday, 22 March 2014

read xml by linq in c#

Reading data from Linq in c#,  It is very simple and less line of code to read data from XML. It consist of XDocument to load the xml data
Need to import the 
using System.Xml.Linq;
@XML Sample
xml version="1.0" encoding="utf-8" ?>
<root>
  <Employee name="Bob" Phonenumber="344343433" >
   
  </Employee>
  <Employee name="julie" Phonenumber="1212121212" >
  </Employee>
 
</root>
@Code Snippet To read XML in C# using Linq;
class Program
    {
        ///
        /// Main method
        ///

        ///
        public static void Main(String[] args)
        {
            //Load xml
            XDocument xdoc = XDocument.Load(@"E://Employee.xml");
            //Run query
            var lv1s = from lv1 in xdoc.Descendants("Employee")
                       select new
                       {
                           name = lv1.Attribute("name").Value,
                           Phonenumber = lv1.Attribute("Phonenumber").Value
                           //  Children = lv1.Descendants("Detail") // it used to read the desedent
                       };
            //Loop through results
            foreach (var lv1 in lv1s)
            {
                Console.WriteLine("Name : " + lv1.name + " -- Phone Number : " + lv1.Phonenumber);
             /*   foreach (var lv2 in lv1.Children)
                    result.AppendLine("     " + lv2.Attribute("name").Value); * // Reading children values*/
            }
        }
    }
@OutPut

No comments:

Post a Comment

Others

You will like to read it