【问题标题】:Insert multiple elements in XmlDocument在 XmlDocument 中插入多个元素
【发布时间】:2016-08-26 01:12:05
【问题描述】:

这是我第一次使用 xmldocument,我有点迷茫。目标是插入:

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

放入我的 XmlDoc 中的特定位置。

到目前为止,我只关注第一个元素

        XmlElement root = Document.CreateElement("appSettings");
        XmlElement id = Document.CreateElement("add");
        id.SetAttribute("key", "FreitRaterHelpLoc");
        id.SetAttribute("value", "");

        root.AppendChild(id);

但这足以添加其余元素吗?例如,这就是我在第 2 行所拥有的

        id = Document.CreateElement("add");
        id.SetAttribute("key", "FreitRaterWebHome");
        id.SetAttribute("value", "http://GPGBYTOPSPL12/");

        root.AppendChild(id);

我不确定这里是否需要 InsertAfter,或者一般来说,获取此文本块的最佳方法是什么。再说一次,XmlDoc 新手

【问题讨论】:

  • 那么...您的代码有效吗?您只是在询问最佳做法吗?
  • 为什么不直接使用Load/LoadXml 方法加载xml,而不是手动构建文档?

标签: c# xml xmldocument


【解决方案1】:

我强烈建议使用 LINQ to XML 而不是 XmlDocument。这是一个更好的 API - 您可以简单地以声明方式创建文档:

var settings = new XElement("appSettings",
    new XElement("add", 
        new XAttribute("key", "FreitRaterHelpLoc"), 
        new XAttribute("value", "")),
    new XElement("add", 
        new XAttribute("key", "FreitRaterWebHome"), 
        new XAttribute("value", "http://GPGBYTOPSPL12/")),
    new XElement("add", 
        new XAttribute("key", "FreitRaterDefaultSession"), 
        new XAttribute("value", ""))
);

或者甚至可以通过声明简单的转换从其他对象生成它的一部分:

var dictionary = new Dictionary<string, string>
{
    {"FreitRaterHelpLoc", ""},
    {"FreitRaterWebHome", "http://GPGBYTOPSPL12/"},
    {"FreitRaterDefaultSession", ""},
};

var keyValues = 
    from pair in dictionary
    select new XElement("add",
        new XAttribute("key", pair.Key), 
        new XAttribute("value", pair.Value));

var settings = new XElement("appSettings", keyValues);

【讨论】:

  • 这更有意义,也更容易,谢谢
猜你喜欢
  • 1970-01-01
  • 2020-10-31
  • 2018-07-26
  • 2023-04-03
  • 1970-01-01
  • 2011-04-21
  • 2021-09-27
  • 2013-09-23
  • 2023-03-05
相关资源
最近更新 更多