Wednesday, April 6, 2011

How to handle XML string %Like% search in C#

Hi, As I know I can search DB with Sql syntax %like%.

Now I am working with XML, how can I handle the same search condition for XML file in C#?

I want to search the string and find it with part of the Keyword. Not the full text of keyword.

   <bookstore>
     <book genre="autobiography">
       <title>The Autobiography of Benjamin Franklin</title>
       <author>
         <first-name>Benjamin</first-name>
         <last-name>Franklin</last-name>
       </author>
       <price>8.99</price>
     </book>
     <book genre="philosophy">
       <title>The Gorgias</title>
       <author>
         <name>Plato</name>
       </author>
       <price>9.99</price>
     </book>
   </bookstore>

Assume I am working with the sample XML above. How can I code in C# to search "%jami%", then return "Benjamin". Thank you.

From stackoverflow
  • Traverse the XML file and do a String.Contains(...).

    Nano HE : @PieterG,Thank you . I found a sample code about String.Containers(). It works quite well as I need.
    allonym : That'll work, but Garett's suggestion of XPath or Linq To XML is the more elegant approach.
  • There are a couple of ways this can be done, depending on the version of .NET you are working with. You can use XPath, or my preference Linq To XML.

    Here are a few useful links:

0 comments:

Post a Comment