简体   繁体   English

C#和XML-搜索XML文件

[英]C# and XML - Searching an XML file

I am having an issue when searching an XML file for a certain key word. 在XML文件中搜索某个关键字时遇到问题。

Here is an example XML file 这是一个示例XML文件

<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. 我有一个GUI应用程序,用户在其中输入他们想要的书的一部分或全名,然后遍历XML文件并找到正确的条目,并给出正确的结果。 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. 我已经尝试过使用XmlTextReader,但我不知道如何使用,任何帮助将不胜感激。

Thankyou. 谢谢。

You can use LINQ to XML: 您可以使用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. 为了使其更易于使用,您应该创建一个Book类来存储数据。
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. 然后,您可以针对Book对象编写LINQ查询。

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. 如果这些是XML文件,则您创建的更多方法是使用System.Xml.Serialization.XmlSerializer保存,然后将XML文档加载到Book类中,然后查询您的类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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