Luke Berry
Luke Berry

Reputation: 1947

C# and XML - Searching an XML file

I am having an issue when searching an XML file for a certain key word.

Here is an example XML file

<books>
    <book>
        <name>BookName</book>
        <price>BookPrice</price>
    </book>
</books>

I have a GUI application where a user enters part of or the full name of the book that they want, it then goes through the XML file and finds the correct entry, and gives out the correct results. The problem is I have no idea how to do this.

I have tried using the XmlTextReader, I just have no idea how, any help would be greatly appreciated.

Thankyou.

Upvotes: 0

Views: 3231

Answers (2)

Skarsnik
Skarsnik

Reputation: 118

If these are XML files that you have created a more oo approach would be to use the System.Xml.Serialization.XmlSerializer to save and then load the XML document into a Book class and then query your classes.

using System.Xml.Serialization;
using System.IO;

// Load the book from the file.
XmlSerializer serializer = new XmlSerializer(typeof(Book));
reader = new StreamReader(filePathName);
Book book = (Book)serializer.Deserialize(reader);
reader.Close();

if (book.Name.Contains(myQuery))
{
    // We have a match.
}

Upvotes: 2

SLaks
SLaks

Reputation: 887415

You can use LINQ to XML:

var xml = new XDocument(...);
var books = xml.Descendants("book");
var matches = books.Where(b => 
    b.Element("name").Value.IndexOf(str, StringComparison.CurrentCultureIgnoreCase) >= 0
);

To make it easier to work with, you should create a Book class to store the data.
You can then write

List<Book> books = xml.Descendants("book")
                      .Select(x => new Book(
                        x.Element("name").Value,
                        (decimal)x.Element("price")
                   ).ToList();

You can then write LINQ queries against the Book objects.

Upvotes: 4

Related Questions