簡體   English   中英

從XML文件讀取特定文本

[英]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.

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