Search code examples
c#xmlxmldocument

Insert multiple elements in XmlDocument


This is my first time ever working with xmldocument and i'm a bit lost. The goal is to insert:

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

into a specific place in my XmlDoc.

so far i've started out just focusing on the first element

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

        root.AppendChild(id);

but is this sufficient for adding the rest of the elements? For example this is what i have for line 2

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

        root.AppendChild(id);

im not sure if InsertAfter would be necessary here, or in general what would be the best way to get this block of text in. Again, XmlDoc rookie


Solution

  • I'd strongly advise using LINQ to XML instead of XmlDocument. It's a much nicer API - you can simply create your document in a declarative manner:

    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", ""))
    );
    

    Or maybe even generate parts of it from other objects by declaring simple transformations:

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