[英]Reading specific text from XML files
我已经创建了一个小的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() + "\n\n";
}
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
System.Xml.XPath。
Xpath支持计数:count(// nodeName)
如果要计算带有特定文本的节点,请尝试
count(//*[text()='Hello'])
请参见如何在C#中使用XPath获取SelectedNode的计数?
顺便说一句,您的函数应该看起来像这样:
private int SearchMultipleTags(string searchTerm, string folderPath) { ...
//...
return i;
}
改为使用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();
尝试使用XPath
:
//var document = new XmlDocument();
int count = 0;
var nodes = document.SelectNodes(String.Format(@"//*[text()='{0}']", searchTxt));
if (nodes != null)
count = nodes.Count;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.