Saturday, March 10, 2012

ASP.Net LINQ XML file search


Extract data from XML document using LINQ technique.

This is the example of LINQ with XML. Here I have used LINQ query to extract data from XML file. And if the string value is equal to 5 then it will display. In this way you can extract data from your XML file using LINQ query.



Step 1)Copy and paste below code in your ASP.Net page

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string fname = "";

        XElement instructors = XElement.Parse(
               @"<instructors>
                   <instructor>Aaron</instructor>
                   <instructor>Fritz</instructor>
                   <instructor>Keith</instructor>
                   <instructor>Scott</instructor>
                 </instructors>"
            );

        IEnumerable<string> query = from n in instructors.Elements("instructor")
                                    where n.Value.Length == 5
                                    orderby n.Value descending
                                    select n.Value;

        foreach (string name in query)
        {
           
            fname = fname +"<br>"+ name;
        }
        this.Label1.Text = fname;



    }
}


No comments:

Post a Comment