簡體   English   中英

使用C#計算xml中一個單詞的出現次數

[英]Count the No of Occurrences of a word in xml using c#

我有一個XML文件,其中必須查找XML文件中一個單詞出現的次數。 考慮一下,我有一個示例XML文件,如下所示

<planes_for_sale>
   <ad>
      <year> 1977 </year>
      <make> &c; </make>
      <model> Skyhawk </model>
      <color> Light blue and white </color>
      <description> New paint, nearly new interior,
            685 hours SMOH, full IFR King avionics </description>
      <price> 23,495 </price>
      <seller phone = "555-222-3333"> Skyway Aircraft </seller>
      <location>
         <city> Rapid City, </city>
         <state> South Dakota </state>
      </location>
   </ad>
   <ad>
      <year> 1965 </year>
      <make> &p; </make>
      <model> Cherokee </model>
      <color> Gold </color>
      <description> 240 hours SMOH, dual NAVCOMs, DME, 
                new Cleveland brakes, great shape </description>
      <seller phone = "555-333-2222"  
              email = "jseller@www.axl.com">
              John Seller </seller>
      <location>
         <city> St. Joseph, </city>
         <state> Missouri </state>
      </location>
   </ad>
    <ad>
      <year> 1968 </year>
      <make> &p; </make>
      <model> Cherokee </model>
      <color> Gold </color>
      <description> 240 hours SMOH, dual NAVCOMs, DME, 
                new Cleveland brakes, great shape </description>
      <seller phone = "555-333-4444"  
              email = "jseller@www.axl.com">
              John Seller </seller>
      <location>
         <city> xxxxx, </city>
         <state> yyyyyy </state>
      </location>
   </ad>
</planes_for_sale>

現在,假設我要檢查xml文件中字符串“ Gold”的出現次數。 使用C#代碼怎么可能?

提前致謝!

根據您的要求, Regex.Matches(File.ReadAllText(myFile), "Gold").Count可以完成這項工作,可能比您自己編寫的任何文件都更有效。 但是,更有趣的問題是找到所有Color屬性為Gold的飛機:)

(哦,我忘記詢問是否區分大小寫,但是您可以在Regex.Matches的第二個參數中指定它)

不要只尋找可能以人名(金幣地址)的黃金。 您的xml中的&符無效並且會出錯。 要獲得正確的結果,請使用xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("ad").Where(x => ((string)x.Element("color")).Trim() == "Gold").ToList();

            int count = results.Count;

        }
    }
}

暫無
暫無

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

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