XML – Search for keyword in repeating elements

I had an XML file where I needed to return all records that contained a specific keyword. Each record has multiple keyword values. My first shot at a LINQ query would only return records where the keyword was found in the first occurrence of the keyword value. The second query will return a record with one or more matches for the keyword value.

*** Sample XML ***

    <Name>Abdominal Pain</Name>
      <Value>ABDOMINAL CRAMPS</Value>
      <Value>ABDOMINAL PAIN</Value>
      <Value>ABDOMINAL WALL PAIN</Value>

*** Incorrect LINQ query

var v = from script in _x.Elements(“Script”)
  where script.Element(“Keywords”).Element(“Value”).Value.Contains(t)
  select new {
   ScriptName = script.Element(“Name”).Value,
   ID = script.Element(“Id”).Value

*** Correct LINQ query

XElement _x = XElement.Load(@”c://File.xml”);
// Keyword to search for
string t = “ABDOMEN”;

var v = from script in _x.Elements(“Record”)
  where script.Element(“Keywords”).Elements(“Value”).Any(tx => tx.Value.Contains(t))
  select new {
   ScriptName = script.Element(“Name”).Value,
   ID = script.Element(“Id”).Value
foreach (var item in v) {
 Console.WriteLine(item.ScriptName + ” ” + item.ID);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: