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);
    }
  }
}