2013-10-18 65 views
2

我試圖將現有的XML文件「嵌入」到另一個「根」XML文件的另一個節點中。假設有一個現有的XML文件的路徑...使用StreamReader中的XElement創建新的XDocument文本

StreamReader reader = new StreamReader(path); 

    string lines = reader.ReadLine(); 
    while (!reader.EndOfStream) 
    { 
     lines = reader.ReadLine(); 
    } 

    XDocument doc = new XDocument(
     new XComment("You can copy and paste or open the XML in Excel."), 
     new XElement("Root", 
      new XElement("logs",lines)) 
    ); 

我結束了這樣的事情:

<Root><logs>&lt;log&gt;&lt;username&gt;otonomy&lt;/

一些解碼編碼需要幫助。

+0

的StreamReader要讀取的純文本;如果文件包含XML,則將其視爲XML,而不是文本。看到MarcinJuraszek的回答 –

回答

3

使用XElement.Load()靜態方法代替:

XDocument doc = new XDocument(
     new XComment("You can copy and paste or open the XML in Excel."), 
     new XElement("Root", 
      new XElement("logs" 
       XElement.Load(path))) 
    ); 

它可以直接把path,所以你不必在所有處理StreamReader

+0

我明白爲什麼人們會說「saweeet!」謝謝! – Par6

1

嘗試:

string lines = File.ReadAllText(path); 

XDocument doc = new XDocument(
    new XComment("You can copy and paste or open the XML in Excel."), 
    new XElement("Root", 
     new XElement("logs", XElement.Parse(lines))));