This is my first post on CodeProject. I am expecting support and suggestions from all CodeProject friends.
I’m impressed with the features of Linear Query and its reliability. I am surprised solving a few problems that weren’t solved using other techniques
but solved using LINQ. Before starting a detailed LINQ tutorial did you check my last post about LINQ? Well, no more talks, let’s start our the next tutorial is on how
to search XML file content using LINQ.
In following few lines, I will teach you how to search content of an XML file using .NET. I got the solution to this problem after a day of practice. So let’s start now.
Using the code
Consider a file named Search.xml with the following content:
<doc id="Doc-abc" title="Abc document"/>
<doc id="Doc-DEF" title="Doc-DEF"/>
<doc id="EFG Document" description="Document of EFT"/>
Great, now add a
TextBox to take user input for search content. This code can search with product title and document title.
Under the text change property or in any button control’s click event, add the following code. To run this code easily, make sure you have an empty XML file named SearchResult.xml, a
DataGridView control named
SrchList, and a
BindingSource control named
BS. This code will display all the matching results in the gridview.
private void TxtSearchString_TextChanged(object sender, EventArgs e)
StringBuilder st= new StringBuilder();
XDocument doc = new XDocument(XDocument.Load("Search.xml"));
var data = from item in doc.Descendants("doc")
title = item.Attribute("title").Value,
DataSet ds = new DataSet();
StringBuilder sr = new StringBuilder();
foreach (var p in data)
if (p.title.ToUpper().Contains(TxtSearchString.Text.ToUpper()) ||
sr.AppendLine("<doc Project-Title =\"" +
p.Ptitle.ToString() + "\" Document-Title=\"" +
p.title.ToString() + "\" />");
TextWriter w = new StreamWriter("searchResult.xml");
if (ds.Tables.Count > 0)
BS.DataSource = ds.Tables;
SrchList.DataSource = BS;
catch (Exception ex)
Yauvaraj Rimal (Prince Rimal) is working in Software Development since early college days, from around 2007. He originally worked on Visual Basic and ASP. Later he worked on PHP, Now working on .Net Technology (Asp.Net, C# and VB.Net).