簡體   English   中英

如何在整個 XML 文件中搜索關鍵字?

[英]How to search entire XML file for keyword?

我正在學習 C#,我想做的一件事是讀入 XML 文件並搜索它。

我找到了一些示例,我可以在其中搜索特定節點(例如,如果它是名稱或 ISBN)以查找特定關鍵字。

我想做的是搜索整個 XML 文件,以便找到關鍵字的所有可能匹配項。

我知道 LIST 允許“包含”來查找關鍵字,是否有類似的功能來搜索 XML 文件?

我使用的是安裝 Visual Studio 時包含的通用 books.xml 文件。

例如,您可以使用LINQ TO XML 此示例在元素和屬性中搜索關鍵字 - 在它們的名稱和值中。

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());

如果您只想搜索關鍵字出現在葉節點的文本中,請嘗試以下操作(使用此示例books.xml ):

string keyword = "com";
var doc = XDocument.Load("books.xml");

var query = doc.Descendants()
    .Where(x => !x.HasElements &&
                x.Value.IndexOf(keyword, StringComparison.InvariantCultureIgnoreCase) >= 0);
foreach (var element in query)
    Console.WriteLine(element);

輸出:

<genre>Computer</genre>
<description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
<genre>Computer</genre>
<title>MSXML3: A Comprehensive Guide</title>
<genre>Computer</genre>
<title>Visual Studio 7: A Comprehensive Guide</title>
<genre>Computer</genre>
<description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>

如果您正在尋找一個您已經知道的關鍵字,您可以將 XML 解析為簡單的文本文件並使用 StreamReader 進行解析。 但是,如果您正在尋找 XML 中的元素,您可以使用 XmlTextReader(),請考慮以下示例:

using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)
        { 
            //do your code here
        }
    }
}

希望能幫助到你。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM