Search code examples
c#xmllinqxmldocument

XMLDocument: Read XDocument and put contents into other XDocument (LINQ)(C#)


Using LinQ, i have the following in XDocument machine2.config

<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>

and i need to get it in a specific place in XDocument machine.config

I first had manually hardcoded the elements, and XPathSelectElement().AddAfterSelf() worked beautifully to get the xml chunk where i wanted it. But I need to get it to read from the file so that it could be changed with a quick edit of the document. Now, with this code

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>

I'm able to add it but it doesn't copy in right format. Instead in machine.config I get

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

when it should be

</configSections>
<appSettings>
...

Anyway I'm pretty lost so if anyone knows of a way to get this from one file to the other in the correct format i would so appreciate it.


Solution

  • Change your code to

    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