Wednesday, June 9, 2010

Using LinQ to query xml

-          Create a xml file with following structure.
<?xml version="1.0" encoding="utf-8" ?>

<Errors>

  <Error voucherId="1" message="Issues while saving data"/>

  <Error voucherId="1" message="Transaction Blocked"/>

  <Error voucherId="1" message="Account is Closed"/>

  <Error voucherId="3" message="This voucher has minumum balance."/>

  <Error voucherId="3" message="Some errors occured while saving the voucher."/>

</Errors>



-          Make sure your code file has following references
using System.Linq;

using System.Xml.Linq;


-          Open Visual Studio 2008 and create a new console application.  Write following code on the program.cs file.
        /// <summary>

        /// Class to represent an error message.  You can have similar class to represent your data

        /// </summary>

        public class Error

        {

            public string VoucherId { get; set; }

            public string ErrorMessage { get; set; }

        }



        static void Main(string[] args)

        {

            //Load XML document on to XDocument object

            XDocument xdoc = XDocument.Load("../../ErrorMessages.xml");



            //Query the XML document and read all the "Error" element.  Prepare a list of Error class from the returned data

            List<Error> errorCollection = (from errors in xdoc.Descendants("Error")

                                           where errors.Attribute("voucherId").Value=="1"

                                          select new Error

                                          {

                                              VoucherId = errors.Attribute("voucherId").Value,

                                              ErrorMessage = errors.Attribute("message").Value

                                          }

                                          ).ToList<Error>();



            //Loop through the returned collection and output the result.

            foreach (Error e in errorCollection)

            {

                Console.WriteLine("Voucher Id: " + e.VoucherId);

                Console.WriteLine("Error Message: " + e.ErrorMessage);

            }

            Console.ReadKey();

        }

    }

-         Execute this console application and it will print the selected nodes from xml


Regards,
Sudhir Kesharwani
Mob: +91 98225 11209

No comments: