如何计算文本文件的出现次数 [英] How to count the occurence of the text file

查看:92
本文介绍了如何计算文本文件的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<Books Type="Science">

</Books>

<Books Type="Story"> 

</Books>

<Books Type="History">

</Books>





这是一个示例文本文件。

在这里,我想计算节点的出现次数,例如Type =Science,Story。



如何使用txt文件中的文本读取



This is a sample text file.
Here I want to count the number of occurrence of the nodes such as Type="Science" ,"Story".

How to do using text reading from txt file

推荐答案

您应该使用XPATH执行此操作(您可以在MSDN或Google上搜索XPATH):



You should use XPATH for doing this (you could search on MSDN or Google about XPATH):

string expresion= "/Books[@Type='Science' or @Type='Story']"; //XPATH expression!

XmlDocument xml = new XmlDocument();
xml.LoadXml(filePath); //Your file path!
XmlNodeList nodeList = xml.SelectNodes(expresion);
int n = nodeList.Count;


您可以使用以下代码:< br $>


You can use below code:

XDocument doc = XDocument.Load(@"C:\XMLFile1.xml");
var query = from ele in doc.Descendants("Books")
            where ele.Attribute("Type").Value == "Science"
            select ele;
Console.WriteLine( query.Count());
Console.Read();





这可以解决您的问题。



谢谢



This should solve your problem.

Thanks


由于这看起来像XML,我建议使用.NET中已经存在的XML读取和分析功能。

看看

LINQ to XML [ ^ ]



System.Xml.Linq命名空间 [ ^ ]
Since this looks like XML, I'd suggest using the XML reading and analysis capabilities already present in .NET.
Look at
LINQ to XML[^]
and
System.Xml.Linq namespace[^]


这篇关于如何计算文本文件的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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