我有一个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#代码怎么可能?
谢谢!
答案 0 :(得分:1)
根据您的要求, X1 X2 X3
1 11202 398 2018
2 11353 216 2017
可以胜任您的工作,可能比您自己编写的任何文件都更有效率。
但是一个更有趣的问题是找到所有Color属性为Gold的飞机:)
(哦,我忘记询问是否区分大小写,但是您可以在Regex.Matches的第二个参数中指定它)
答案 1 :(得分:0)
不仅要寻找可能以人名(金币地址)的黄金。您的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;
}
}
}