Click here to Skip to main content
15,884,986 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Search XML Using LINQ in .NET

Rate me:
Please Sign up or sign in to vote.
3.33/5 (2 votes)
5 Sep 2012CPOL1 min read 11.4K   4   2
How to search XML content using LINQ in .NET.

Introduction

This is my first post on CodeProject. I am expecting support and suggestions from all CodeProject friends.

Background 

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:

XML
<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 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.  

C#
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;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Nepal Nepal
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

 
GeneralMy vote of 2 Pin
stooboo5-Sep-12 14:13
stooboo5-Sep-12 14:13 
Linq != Linear Query
Linq == Language-Integrated Query

There is a LOT going on in this little method.. and I think it's suffering

Consider naming your variables better e.g. why is a StringBuilder called 'sr' ??
Consider why are you calling 'TxtSearchString.Text.ToUpper()' so many times ?
Consider putting the 'TextWriter w = new StreamWriter("searchResult.xml");' etc in a using statement - that way you won;t have to worry about forgetting to dispose it
Consider using XDocument etc. for writing XML objects
Consider what the tyr-catch is bringing to your party (or not)
Consider why you are assigning an instance of StreamWriter into a variable of type TextWriter
SuggestionMy 4 - respect compiler warnings: do dispose disposable objects, don't do catch-rethrow Pin
Andreas Gieriet5-Sep-12 9:58
professionalAndreas Gieriet5-Sep-12 9:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.