【问题标题】:XMLDocument: Read XDocument and put contents into other XDocument (LINQ)(C#)XMLDocument:读取 XDocument 并将内容放入其他 XDocument (LINQ)(C#)
【发布时间】:2016-09-14 17:26:36
【问题描述】:

使用 LinQ,我在 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>

我需要将它放在 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>
...

无论如何,我很迷茫,所以如果有人知道一种方法可以以正确的格式从一个文件到另一个文件,我将不胜感激。

【问题讨论】:

    标签: c# xml linq xmldocument


    【解决方案1】:

    将您的代码更改为

    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
    

    【讨论】:

    • 就像一个魅力,没有考虑将其作为一个元素来阅读。谢谢:)
    • 我很高兴,@M.Doe 你现在可以对答案投票了。
    猜你喜欢
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    相关资源
    最近更新 更多