Showing posts with label Linq To XML. Show all posts
Showing posts with label Linq To XML. Show all posts

February 3, 2011

LINQ TO XML


How to use Linq in ASP.NET App  refer my below post
http://www.dotnetissues.com/2011/02/select-query-linq-to-sql-example.html

To fetch the data from XML , below is the code using LINQ



Default6.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs" Inherits="Default6" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server"/>
    </div>
    </form>
</body>
</html>

Default6.aspx.cs


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


public partial class Default6 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataClassesDataContext db = new DataClassesDataContext();
        var results = from o in XElement .Load (MapPath ("XMLfile.xml")).Elements ("student")
                      select o.Value;


        GridView1.DataSource = results;
        GridView1.DataBind();
    }
}




XMLfile.xml


<?xml version="1.0" encoding="utf-8" ?>
<students>
            <student>
            <name>  ABC</name>
            <Address> ABC Address</Address>
            <Email> a@a.com  </Email>
           </student>


          <student>
            <name> XYZ </name>
            <Address>XYZ Address </Address>
            <Email> x@x.com  </Email>
          </student>


          <student>
            <name>  LMN</name>
            <Address> LMN address</Address>
            <Email>   l@l.com</Email>
          </student>




          <student>
            <name> PQR </name>
            <Address>PQR address </Address>
            <Email>  p@p.com </Email>
          </student>
</students>
Below is the o/p