2016-09-14 65 views
0

使用LINQ,我有在下面的XDocument machine2.config的XMLDocument:閱讀的XDocument,並把內容轉換成其他的XDocument(LINQ)(C#)

<appSettings> 
<add key="FreitRaterHelpLoc" value="" /> 
<add key="FreitRaterWebHome" value="http://GPGBYTOPSPL12/" /> 
<add key="FreitRaterDefaultSession" value="" /> 
<add key="FreitRaterTransferMode" value="Buffered" /> 
<add key="FreitRaterMaxMsgSize" value="524288" /> 
<add key="FreitRaterMaxArray" value="16384" /> 
<add key="FreitRaterMaxString" value="32768" /> 
<add key="FreitRaterSvcTimeout" value="60" /> 
</appSettings> 

,我需要得到它在的XDocument一個特定的地方machine.config

我第一次手動硬編碼的元素,和XPathSelectElement()。AddAfterSelf()工作得很好,以獲得我想要的xml塊。但我需要從文件中讀取它,以便可以通過快速編輯文檔來更改它。 現在,有了這個代碼

XDocument doc = XDocument.Load("machine.config"); 

XDocument AppSettings = XDocument.Load("machine2.config"); 
string content = AppSettings.ToString(); 

doc.XPathSelectElement("configuration/configSections").AddAfterSelf(content); //need it to insert after </configSections> 

我能添加它,但它不正確的格式複製。相反,在machine.config中,我得到

</configSections>&lt;appSettings&gt;&lt;add key="FreitRaterHelpLoc" //etc 

當它應該是

</configSections> 
<appSettings> 
... 

無論如何,我很迷失,如果任何人的方式知道在正確的從一個文件中得到這個其他格式我會很感激。

回答

0

更改您的代碼

XDocument doc = XDocument.Load("machine.config"); 
XElement AppSettings = XElement.Load("machine2.config"); //NB: not XDocument 
doc.XPathSelectElement("configuration/configSections").AddAfterSelf(AppSettings); 
doc.Save("machine.config"); //Of course I'm sure you had this line somewhere 
+0

工作就像一個魅力,也沒多想閱讀它作爲一個元素。謝謝:) –

+0

這是我的榮幸,@ M.Doe你現在可能投票答案。 –