2
2011
Search XML Using LINQ in .Net
I’m impressed with the features of Linear Query and it’s reliability. I wonder myself on solving few problems that weren’t solved using other techniques are solved using LINQ myself. Before starting detail LINQ tutorial did you check my last Post about LINQ? It not Check it here. Well, no more talks, let’s start our next tutorial to search xml file content using LINQ.
In following few lines, i will teach you how to search content of xml file using .Net. I got solution to this problem after 1 day of practice. So let’s start now.
Consider a file named Search.xml with the following content.
<strong>
</strong><productlist title="ABC">
<product title="ABC-Title">
<doc id="Doc-abc" title="Abc document"/>
</product>
<product title="DEF">
<doc id="Doc-DEF" title="Doc-DEF"/>
</product>
<product title="EFG">
<doc id="EFG Document" description="Document of EFT"/>
</product>
</productlist>
Great, now add a Textbox to take user input for search content. This code can search with product title and document title.
Under a 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, datagridview control named SrchList and BindingSource control named BS. This code will display all the matching
result 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")
select new
{
Ptitle=item.Parent.Attribute("title").Value,
title = item.Attribute("title").Value,
};
DataSet ds = new DataSet();
StringBuilder sr = new StringBuilder();
sr.Append("<product>");
foreach (var p in data)
{
if (p.title.ToUpper().Contains(TxtSearchString.Text.ToUpper()) || p.Ptitle.ToUpper().Contains(TxtSearchString.Text.ToUpper()))
sr.AppendLine("<doc Project-Title =\"" + p.Ptitle.ToString() + "\" Document-Title=\"" + p.title.ToString() + "\" />");
}
sr.Append("</product>");
TextWriter w = new StreamWriter("searchResult.xml");
w.Write(sr.ToString());
w.Flush();
w.Close();
try
{
ds.ReadXml("searchResult.xml");
if (ds.Tables.Count > 0)
{
BS.DataSource = ds.Tables[0];
SrchList.DataSource = BS;
}
}
catch (Exception ex)
{
throw;
}
}
Thanks ! ! !
Please, do post your comment regarding the post, and if you find helpful refer to your friend as well. Have a happy coding. .

An article by
awesom work brother….