如何在整个XML文件中搜索关键字? [英] How to search entire XML file for keyword?

查看:95
本文介绍了如何在整个XML文件中搜索关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C#,而我要尝试做的一件事是在XML文件中读取并搜索它.

Im learning C# and one of the things I am trying to do is read in an XML file and search it.

我找到了一些示例,可以在这些示例中搜索特定节点(例如,名称或ISBN)以查找特定关键字.

I have found a few examples where I can search specific nodes (if its a name or ISBN for example) for specific key words.

我想要做的是搜索整个XML文件,以查找关键字的所有可能匹配项.

What I was looking to do was to search the entire XML file in order to find all possible matches of a keyword.

我知道LIST允许包含"查找关键字,是否有类似的功能来搜索XML文件?

I know LIST allows a "contains" to find keywords, is there a similar function for searching an XML file?

我使用安装Visual Studio时随附的通用books.xml文件.

Im using the generic books.xml file that is included when visual studio is installed.

推荐答案

例如,您可以使用 LINQ TO XML .本示例在元素和属性(名称和值)中搜索关键字.

For example, you could use LINQ TO XML. This example searches for the keyword both in elements and attributes - in their names and values.

private static IEnumerable<XElement> FindElements(string filename, string name)
{
    XElement x = XElement.Load(filename);
    return x.Descendants()
            .Where(e => e.Name.ToString().Equals(name) ||
                        e.Value.Equals(name) ||
                        e.Attributes().Any(a => a.Name.ToString().Equals(name) || 
                                                a.Value.Equals(name)));
}

并使用它:

string s = "search value";
foreach (XElement x in FindElements("In.xml", s))
    Console.WriteLine(x.ToString());

这篇关于如何在整个XML文件中搜索关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆