在XmlDocument中插入多个元素

本文关键字:元素 插入 XmlDocument | 更新日期: 2023-09-27 18:03:58

这是我第一次使用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 rookie

在XmlDocument中插入多个元素

我强烈建议使用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);