2015-01-08 67 views
0

這裏我開發了一個簡單的工具,它讀取一個xml文件並刪除沒有價格的節點。現在它讀取一個XML文件。從多行文本框中讀取多個文件

但我需要讀取多個XML文件並同時解析所有文件。有人可以幫助我做同樣的事情嗎?

private void LoadNewFile() 
{ 
    OpenFileDialog XmlFile = new OpenFileDialog(); 
    XmlFile.Title = "Browse XML File"; 
    string FilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
    XmlFile.InitialDirectory = FilePath; 
    XmlFile.Filter = "XML Files|*.xml"; 
    System.Windows.Forms.DialogResult dr = XmlFile.ShowDialog(); 
    if (dr == DialogResult.OK) 
    { 
     OldFilePath = XmlFile.FileName; 
    } 
} 

private void RemovePrice() 
{ 
    XmlDocument xmldoc = new XmlDocument(); 
    XmlNodeList emptyElements; 
    xmldoc.Load(NewFilePath); 
    emptyElements = xmldoc.GetElementsByTagName("book"); 
    for (int i = emptyElements.Count - 1; i >= 0; i--) 
    { 
     string price= emptyElements[i]["price"].InnerText; 
     if (string.IsNullOrEmpty(price)) 
      emptyElements[i].ParentNode.RemoveChild(emptyElements[i]); 
    } 
    xmldoc.Save(OldFilePath); 
} 

回答

1

要加載ultiple文件使用Multiselect屬性並將其設置爲true。並行處理可以通過使用Parallel.ForEach循環來完成。然後你稍微重寫你的主要方法來在這個框架中運行。下面的示例代碼(未經測試):

private void ProcessFiles() 
    { 
     // This property should be set somewhere in the c-tor. 
     // It's here just for presentation purposes. 
     this.openFileDialog1.Multiselect = true; 

     DialogResult dr = this.openFileDialog1.ShowDialog(); 
     if (dr == System.Windows.Forms.DialogResult.OK) 
     { 
      // Read the files 
      System.Threading.Tasks.Parallel.ForEach(
       this.openFileDialog1.FileNames, 
       file => 
        { 
         string oldFilePath = file; 
         string newFilePath = "Processed" + file; 
        }); 
     } 
    } 

    private void RemovePrice(string oldFilePath, string newFilePath) 
    { 
     XmlDocument xmldoc = new XmlDocument(); 
     XmlNodeList emptyElements; 
     xmldoc.Load(newFilePath); 
     emptyElements = xmldoc.GetElementsByTagName("book"); 
     for (int i = emptyElements.Count - 1; i >= 0; i--) 
     { 
      string price = emptyElements[i]["price"].InnerText; 
      if (string.IsNullOrEmpty(price)) 
       emptyElements[i].ParentNode.RemoveChild(emptyElements[i]); 
     } 
     xmldoc.Save(oldFilePath); 
    } 
+0

可能要指出''Parallel'在'System.Threading.Tasks'中。只是爲了搶先別人的問題。 – JClaspill

+1

@JClaspill有道理。實際上我添加了整個路徑而不是使用語句。 – PiotrWolkowski