简体   繁体   中英

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.

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.

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM