在XmlDocument中插入多个元素

时间:2016-08-26 01:12:06

标签: c# xml xmldocument

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

1 个答案:

答案 0 :(得分: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);
相关问题