0

複数の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クラスを使用してコードを提案できますか。

よろしくお願いいたします。MayurAlaspure

4

3 に答える 3

0

使用してみてくださいXPath

//var document = new XmlDocument();
int count = 0;
var nodes = document.SelectNodes(String.Format(@"//*[text()='{0}']", searchTxt));
if (nodes != null)
    count = nodes.Count;
于 2012-10-10T05:48:53.473 に答える
0

System.Xml.XPath。

Xpath はカウントをサポートします: count(//nodeName)

特定のテキストを持つノードを数えたい場合は、試してください

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

C# で XPath を使用して SelectedNode のカウント数を取得する方法を参照してください。

ところで、関数はおそらく次のようになります。

private int SearchMultipleTags(string searchTerm, string folderPath) { ...
      //...
      return i;
}
于 2012-10-10T05:25:04.443 に答える
0

代わりに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();
于 2012-10-10T05:26:02.850 に答える