Sunday, December 19, 2010

LINQ - Retrive data from XML using Linq to XML

LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. LINQ to XML uses the latest .NET Framework language capabilities and is comparable to an updated, redesigned Document Object Model (DOM) XML programming interface.

LINQ to XML is a built-in LINQ data provider available in .NET 3.5. It is offered via the System.Xml.Linq namespace. LINQ to XML allows you to create, read, and write XML-based data. The XML data source may be a file, in-memory XML, or a remote resource accessed via protocols like HTTP.

Let see how to retrive data from xml.

Step 1
Create a web application and give the solution name as SolLinqToXMLRetriveData.

Step 2
In App_Data folder insert a XML file and give the file name as Student.xml.

Step 3
The XML in the following example defines an XML document with a root node called Students. This root node contains one or more nodes called Student that include elements called ID,FirstName,LastName and Location.


<?xml version="1.0" encoding="utf-8"?>
<Students>

  <Student>
    <ID>1</ID>
    <FirstName>Bhushan</FirstName>
    <LastName>Pawar</LastName>
    <Location>Thane</Location>
  </Student>

  <Student>
    <ID>2</ID>
    <FirstName>Ramdas</FirstName>
    <LastName>Bhosale</LastName>
    <Location>Thane</Location>
  </Student>
  
 <Student>
  <ID>3</ID>
  <FirstName>Kishor</FirstName>
  <LastName>Naik</LastName>
  <Location>Thane</Location>
 </Student>

  <Student>
    <ID>4</ID>
    <FirstName>Koste</FirstName>
    <LastName>Budinoski</LastName>
    <Location>Skopje</Location>
  </Student>

  <Student>
    <ID>5</ID>
    <FirstName>Bhavesh</FirstName>
    <LastName>Pisat</LastName>
    <Location>Thane</Location>
  </Student>


  <Student>
  <ID>6</ID>
  <FirstName>Kedar</FirstName>
  <LastName>Despande</LastName>
  <Location>Thane</Location>
 </Student>
 
</Students>

Step 4
Add a gridview on page for view the content of XML data,it is look like this

<asp:ScriptManager ID="ScriptManger1" runat="server">
        </asp:ScriptManager> 
    
        <asp:UpdatePanel ID="UpdatePanel" runat="server">
            <ContentTemplate>
                
                <asp:GridView ID="gvStudent" runat="server" BackColor="White" 
                    BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" 
                    EnableModelValidation="True" ForeColor="Black" GridLines="Vertical">
                    <AlternatingRowStyle BackColor="#CCCCCC" />
                    <FooterStyle BackColor="#CCCCCC" />
                    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                </asp:GridView>

            </ContentTemplate>
        </asp:UpdatePanel>

Step 5
Create a StudentModel  class in App_Code folder.it is an entity class,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


public class StudentModel
{
    #region Constructor
    public StudentModel()
    {
    }
    #endregion

    #region Property

    public int ID
    {
        get;
        set;
    }

    public String FirstName
    {
        get;
        set;
    }

    public String LastName
    {
        get;
        set;
    }

    public String Location
    {
        get;
        set;
    }

    #endregion
}

Step 6
Create a StudentDAL static class in App_Code folder for retriving an Student data from XML,it is look like this


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

/// <summary>
/// Retrive Data from XML file
/// </summary>
public static class StudentDAL
{
    #region Methods


    /// <summary>
    /// Get all Student Data from XML
    /// </summary>
    /// <returns>List</returns>
    public static List<StudentModel> GetAllStudentData()
    {
        try
        {
            // Load Xml Document
            XDocument XDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/Student.xml"));

            // Query for retriving all Studnet data from XML
            var Query = (from Q in XDoc.Descendants("Student")
                         select new StudentModel
                         {
                             ID = Convert.ToInt32(Q.Element("ID").Value),
                             FirstName = Convert.ToString(Q.Element("FirstName").Value),
                             LastName = Convert.ToString(Q.Element("LastName").Value),
                             Location = Convert.ToString(Q.Element("Location").Value)
                         }
                           ).ToList<StudentModel>();

            return Query; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Get Student data by FirstName
    /// </summary>
    /// <param name="FirstName">Specify First Name</param>
    /// <returns>List</returns>
    public static List<StudentModel> GetStudentDataByName(String FirstName)
    {
        try
        {
            // Load Xml Document
            XDocument XDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/Student.xml"));

            // Query for retriving Student data from XML by given first name
            var Query = (from Q in XDoc.Descendants("Student")
                         where Q.Element("FirstName").Value == FirstName
                         select new StudentModel
                         {
                             ID = Convert.ToInt32(Q.Element("ID").Value),
                             FirstName = Convert.ToString(Q.Element("FirstName").Value),
                             LastName = Convert.ToString(Q.Element("LastName").Value),
                             Location = Convert.ToString(Q.Element("Location").Value)
                         }
                           ).ToList<StudentModel>();

            return Query;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion
}

Step 7
Bind the student data in gridview.it is look like this

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                BindAllStudentData(); // Bind All Student data in gridview

                //BindStudentDataByName("Kedar"); // Bind a Single Data.
            }
        }
        catch (Exception)
        { 
        }
    }

    #region Methods

    /// <summary>
    /// Bind All Student data in GridView
    /// </summary>
    private void BindAllStudentData()
    {
        try
        {
            List<StudentModel> ListStudentObj = StudentDAL.GetAllStudentData();

            if (ListStudentObj != null)
            {
                if (ListStudentObj.Count > 0)
                {
                    gvStudent.DataSource = ListStudentObj;
                    gvStudent.DataBind(); 
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Bind Student data in grid view by given first name
    /// </summary>
    /// <param name="FirstName">Specify the First Name</param>
    private void BindStudentDataByName(String FirstName)
    {
        try
        {
            List<StudentModel> ListStudentObj = StudentDAL.GetStudentDataByName(FirstName);

            if (ListStudentObj != null)
            {
                if (ListStudentObj.Count > 0)
                {
                    gvStudent.DataSource = ListStudentObj;
                    gvStudent.DataBind(); 
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }
    #endregion
}

Run the project.

Download
Download Source Code

Many developers using LINQ to SQL over regular ADO.NET to work with backend databases; however, there are also a lot of developers who seem happy with the LINQ alternative to working with XML. LINQ to XML is a much simpler and often intuitive approach to XML data, and it is more efficient than using the DOM API via the XmlDocument object. It also brings a database-type approach to XML with the select,insert,update,delete, where, and from clauses for operation on data.

No comments:

Post a Comment