Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 849
  • Last Modified:

LINQ to XML Use Of Contains For String Compare In Where

Hello everyone.
I am trying to check for the existence of a string within the value of an XML element while in a WHERE statement but am having no success.  I am trying to do this in C# with Visual Studio 8.

Here is a sample of the XML file:

<?xml version="1.0" encoding="utf-8"?>
<Books>
  <Book>
    <Title>Programming with C</Title>
    <Author>Author 1</Author>
    <Publisher>Publisher 1</Publisher>
  </Book>
  <Book>
    <Title>Working with C</Title>
    <Author>Author 2</Author>
    <Publisher>Publisher 2</Publisher>
  </Book>
  <Book>
    <Title>How to program C</Title>
    <Author>Author 3</Author>
    <Publisher>Publisher 3</Publisher>
  </Book>
</Books>

What I want to do is to search for elements whose Title contains the substring "program".  Below is the sample code I tried to use but did not work:
=======================================================================
using System.Linq;
using System.Xml.Linq;

XElement doc = XElement.Load("C:\\ProgrammingBooks.xml");
var ProgrammingBooks = from row in doc.Elements("Book")
                         where ((string)row.Element("Title")).ToUpper().Contains("PROGRAM")
                         select row;
MessageBox.Show("Matched Books: " + ProgrammingBooks.Count().ToString());
=======================================================================
When I check the results I always end up with an empty result so I guess the where clause is not working.  If I take the where clause out then I get all the rows. I suppose I could doe the filtering in a subsequent ForEach loop but I would like to see first if I can get the where clause to work.  The end result should be 2 rows that match which are element 1 and 3 from the file.

Thanks in advance.
0
zonkerman
Asked:
zonkerman
  • 2
1 Solution
 
Sreedhar VengalaCommented:
Try this:

from row in doc.Descendants("Book") where ((string)row.Element("Title")).ToUpper().Contains("PROGRAM") select row;
0
 
Sreedhar VengalaCommented:
XElement doc = XElement.Load("C:\\ProgrammingBooks.xml");
            IEnumerable<XElement> elements = from row in doc.Descendants("Book") where ((string)row.Element("Title")).ToUpper().Contains("PROGRAM") select row;

            foreach (var element in elements)
            {
                Console.Write(element);
            }
            Console.ReadKey();

Output: as in attached .jpg

output.jpg
0

Featured Post

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now