Querying a simple XML file using LINQ

The below demo shows how to query a simple xml file using LINQ.


First create an xml file as below and name it as Countries.xml


<?xml version="1.0" encoding="utf-8" ?>
<Countries>
  <Country Id ="1">
    India
  </Country>
  <Country Id ="2">
    U.S.A
  </Country>
  <Country Id ="3">
    China
  </Country>
  <Country Id ="4">
    U.K
  </Country>
</Countries>


Then write the code as below to query xml



using System;
using System.Linq;
using System.Xml.Linq;


public partial class Linq_QueryXMLUsingLINQ : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    XElement xEle = XElement.Load(@"D:\Countries.xml");

    var list = from l in xEle.Elements("Country")
               where ((string)l.Element("Name")).Trim() == "India"
               select l.Element("Name");

    foreach (var item in list)
    {
      Response.Write(item);
    }
  }
}

Hello LINQ

Below is a simple demo of LINQ which prints all the items in the string array.

using System;
using System.Linq;

public partial class Linq_HelloLinq : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    string[] greetings = { "Hello World", "Hello LINQ", "Hello" };

    var greetingsList = from l in greetings select l;

    foreach (var greeting in greetingsList)
    {
      Response.Write(greeting + "<br>");
    }
  }
}

Important things to note are:
1. using System.Linq;
2. var greetingsList = from l in greetings select l;

Rest all is pretty straight forward.

After you are done with doing the above, try adding a where condition to it as below.


using System;
using System.Linq;

public partial class Linq_HelloLinq : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    string[] greetings = { "Hello World", "Hello LINQ", "Hello" };

    var greetingsList = from l in greetings where l.EndsWith("World") select l;

    foreach (var greeting in greetingsList)
    {
      Response.Write(greeting + "<br>");
    }
  }
}

Thats it here ends our simple linq demo.