chilly8063
chilly8063

Reputation: 191

How to search an entire XML file for a keyword?

I'm learning C# and one of the things I am trying to do is read in an XML file and search it.

I have found a few examples where I can search specific nodes (if it's a name or ISBN for example) for specific keywords.

What I was looking to do was to search the entire XML file in order to find all possible matches of a keyword.

I know LIST allows a "contains" to find keywords, is there a similar function for searching an XML file?

I'm using the generic books.xml file that is included when Visual Studio is installed.

Upvotes: -1

Views: 10092

Answers (3)

horgh
horgh

Reputation: 18553

For example, you could use LINQ TO XML. This example searches for the keyword both in elements and attributes - in their names and values.

private static IEnumerable<XElement> FindElements(string filename, string name)
{
    XElement x = XElement.Load(filename);
    return x.Descendants()
            .Where(e => e.Name.ToString().Equals(name) ||
                        e.Value.Equals(name) ||
                        e.Attributes().Any(a => a.Name.ToString().Equals(name) || 
                                                a.Value.Equals(name)));
}

and use it:

string s = "search value";
foreach (XElement x in FindElements("In.xml", s))
    Console.WriteLine(x.ToString());

Upvotes: 0

jomsk1e
jomsk1e

Reputation: 3625

If you are looking for a keyword that you already know, you can parse the XML just as simple text file and use StreamReader for parsing it. But if you are looking for an element in XML you can use XmlTextReader(), please consider this example:

using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)
        { 
            //do your code here
        }
    }
}

Hope it helps. :)

Upvotes: 0

Fung
Fung

Reputation: 3558

If you only want to search for keyword appear in leaf nodes' text, try the following (using this sample books.xml):

string keyword = "com";
var doc = XDocument.Load("books.xml");

var query = doc.Descendants()
    .Where(x => !x.HasElements &&
                x.Value.IndexOf(keyword, StringComparison.InvariantCultureIgnoreCase) >= 0);
foreach (var element in query)
    Console.WriteLine(element);

Output:

<genre>Computer</genre>
<description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
<genre>Computer</genre>
<title>MSXML3: A Comprehensive Guide</title>
<genre>Computer</genre>
<title>Visual Studio 7: A Comprehensive Guide</title>
<genre>Computer</genre>
<description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>

Upvotes: 0

Related Questions