2012-10-10 41 views
0

我創建了一個小型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() + "\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

+0

:你是怎麼試試MAYUR?你以前的帖子http://stackoverflow.com/questions/12776198/reading-multiple-xml-files也有非常相同的代碼片段。在提問之前你嘗試了什麼。 –

+0

@MilindThakkar:那個是用於特定標記,現在我正在尋找XML文件中的特定文本。並感謝您的上一個答案它的作品,我只使用您的代碼。 –

+0

Mayur兩點:其一,我看不到在另一個問題和這個問題給出的代碼片段中有任何改變。所以在問這裏問題之前,你懷疑你試圖做什麼。其次,如果你對任何人的回答感到滿意,你應該將其標記爲「答案」和/或「upvote」.- Milind –

回答

0

使用LINQ2XML instead..It的簡單和完整的更換,以行吟詩人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(); 
+0

非常感謝你的代碼給了我XML文件中特定標記的計數。但我想搜索XML文件中的特定文本。 –

+0

@MayurAlaspure查看ans – Anirudha

+0

的第二部分代碼非常感謝。 :) –

0

System.Xml.XPath。

Xpath的支持計數:計數(//節點名稱)

如果你要計算特定文本節點,嘗試

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

How to get count number of SelectedNode with XPath in C#?

順便說一句,你的函數應可能看起來更多這樣的:

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

嘗試使用XPath

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