Question

How to add the collection of items to XML Document ? Something I started trying, but it's wrong! I'll be grateful for the link on the Internet at a good tutorial too. Also, It is assumed that the iteration will be some elements.

Such code:

public static void Create_Interfaces()
{
      XDocument Interfaces;
       Interfaces = XDocument.Load("Interfaces.xml");
    List<string> intf = new List<string>{"em0","em1","em2"};

    foreach (var i in intf)
    {
        Interfaces = new XDocument(
      new XElement("Interfaces",
        new XElement("Interface",
          new XElement("name", i),
          new XElement("vlan-tagging", XElement.EmptySequence),
          new XElement("unit",
          new XElement("vlan-id", "10"),
          new XElement("family", new XElement("inet", new XElement("address", new XElement("name", "10.10.1.23/24"))))))));
    }
    Interfaces.Save("Interfaces.xml");

}
Was it helpful?

Solution

Get your root element add new elements to it then save it:

var rootElement = Interfaces.Root;

foreach (var i in intf)
{
    var element = new XElement("Interface",
                new XElement("name", i),
                new XElement("vlan-tagging", XElement.EmptySequence),
                new XElement("unit",
                    new XElement("vlan-id", "10"),
                    new XElement("family",
                        new XElement("inet",
                            new XElement("address",
                                new XElement("name", "10.10.1.23/24"))))));

   rootElement.Add(element);
}

rootElement.Save("Interfaces.xml");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top