正在从XML文件中读取特定文本



我创建了一个小型XML工具,它可以从多个XML文件中统计特定的XML标记。

其代码如下:

public void SearchMultipleTags()
{
if (txtSearchTag.Text != "")
{
try
{
//string str = null;
//XmlNodeList nodelist;
string folderPath = textBox2.Text;
DirectoryInfo di = new DirectoryInfo(folderPath);
FileInfo[] rgFiles = di.GetFiles("*.xml");
foreach (FileInfo fi in rgFiles)
{
int i = 0;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(fi.FullName);
//rtbox2.Text = fi.FullName.ToString();
foreach (XmlNode node in xmldoc.GetElementsByTagName(txtSearchTag.Text))
{
i = i + 1;
//
}
if (i > 0)
{
rtbox2.Text += DateTime.Now + "n" + fi.FullName + " nInstance: " + i.ToString() + "nn";
}
else 
{
//MessageBox.Show("No Markup Found.");
}
//rtbox2.Text += fi.FullName + "instances: " + str.ToString();
}
}
catch (Exception)
{
MessageBox.Show("Invalid Path or Empty File name field.");

}
}
else
{
MessageBox.Show("Dont leave field blanks.");
}
}

这段代码向我返回用户想要的多个XML文件中的标记计数。

现在,我想搜索XML文件中存在的特定文本及其计数。

你能建议使用XML类的代码吗。

感谢和问候,Mayur Alaspure

请改用LINQ2XML。。它很简单,完全取代了其他XML API的

XElement doc = XElement.Load(fi.FullName);
//count of specific XML tags
int XmlTagCount=doc.Descendants().Elements(txtSearchTag.Text).Count();
//count particular text
int particularTextCount=doc.Descendants().Elements().Where(x=>x.Value=="text2search").Count();

System.Xml.XXPath.

Xpath支持计数:count(//nodeName)

如果要计算具有特定文本的节点,请尝试

count(//*[text()='Hello'])

请参阅如何在C#中使用XPath获取SelectedNode的计数?

顺便说一下,你的函数可能看起来更像这样:

private int SearchMultipleTags(string searchTerm, string folderPath) { ...
//...
return i;
}

尝试使用XPath:

//var document = new XmlDocument();
int count = 0;
var nodes = document.SelectNodes(String.Format(@"//*[text()='{0}']", searchTxt));
if (nodes != null)
count = nodes.Count;

最新更新