2012-02-07 62 views
2

我想開發一個項目,在其中執行一系列過程。我想從一個目錄加載所有特定類型的文件(* .xhtml)。這些文件應該在標籤中打開。我想搜索一個特定的標籤,並用所有文件中的另一個標籤替換查找和替換功能。如何適應這一點。加載特定目錄的多個文件,並找到並替換所有文件中的功能

+0

很難說(至少對我而言)你在做什麼。您能否請澄清這個問題? – 2012-02-07 10:49:55

+0

是的。它是什麼類型的項目? WinForms,WPF,還是你在做一個CMS? – Oybek 2012-02-07 10:52:16

+0

這是一個Windows窗體應用程序 – 2012-02-07 10:56:31

回答

2

那麼問題是什麼?

  1. 搜索文件:

    var files = DirectoryInfo.GetFiles("*.xhtml", SearchOption.AllDirectories)

  2. 負載在標籤中。在Windows窗體中不是一個大的專業版,但我認爲它就像爲每個找到的文件的一些標籤容器添加新的選項卡控件。

  3. 查看Oybek關於最後一點的回答!

希望它有幫助。

+0

這是一個非常好的答案,除了第3點。[永遠永遠不會永遠不會使用正則表達式的XML/HTML](http://stackoverflow.com/questions/1732348/regex-match-開放式標籤,除了-XHTML-自足標籤)。 – Oybek 2012-02-07 11:10:49

+0

好趕:)謝謝 – 2012-02-07 11:45:21

1

就IO而言,它非常簡單,讀取目錄,迭代文件和讀取內容。

以下代碼片段替換了xml的節點。

var data = @"<foo> 
    <items> 
     <itemToReplace> 
      <itemContent /> 
     </itemToReplace> 
    </items> 
</foo>"; 
     // Load your document 
     var doc = XDocument.Parse(data); 
     // Get the root 
     var root = doc.Element("items"); 
     // Get all tags that you want to replace 
     var repls = doc.Descendants("itemToReplace").ToList(); 
     // Iterate over 
     foreach (var item in repls) { 
      // prepare a new element as a replacement for your target. 
      // Content will be the same as the content of the element being replaced. 
      var newElement = new XElement("newElement", item.DescendantNodes()); 
      // add the element right after the tag to be replaced 
      item.AddAfterSelf(newElement); 
      // finally remove the tag. 
      item.Remove(); 
     } 
     MessageBox.Show(doc.ToString()); 

itemToReplacenewElement取代。正如你所說的XHTML,我認爲有一種格式良好的XML/HTML可以通過linq2xml進行分析。乾杯。

相關問題