Home > Back-end >  C#: How to add Elements to XML using c# & foreach loop
C#: How to add Elements to XML using c# & foreach loop

Time:01-08

I´ve got an xml file looking like this:

<Configuration>
  <Elements>
    <Element>
      <Value1>7</Value1>
    </Element>
    <Element>
      <Value1>3</Value1>
    </Element>
  </Elements>
</Configuration>

I now want to add a Value Element on top of each Element, so that in the end, the xml looks like this:

<Configuration>
  <Elements>
    <Element>
      <Value0>17</Value0>
        <Value1>7</Value1>
    </Element>
    <Element>
      <Value0>13</Value0>
      <Value1>3</Value1>
    </Element>
  </Elements>
</Configuration>

I tried the following in c#:

        XmlDocument doc = new XmlDocument();
        doc.Load("config.xml");


        XmlElement newelem = doc.CreateElement("Value0");
        
        newelem.InnerText = newValue;

        foreach (XmlNode node in doc.GetElementsByTagName("Element"))
        {
            node.InsertBefore(newelem, node.FirstChild);
        }

This adds the new Value, but only to one Element. How can I do it, so that it will be added to every Element? Maybe there is a completely different approach to this. I hope one can understand what I`m trying, thanks in advance!

CodePudding user response:

Create the element in the for loop. Here's some working code, using XPath.

foreach( XmlElement ndNode in xml.SelectNodes( "//Elements/Element")) {
    XmlElement newelem = xml.CreateElement("Value0");
    newelem.InnerText = "test";
    ndNode.InsertBefore(newelem, ndNode.FirstChild);
}
  •  Tags:  
  • Related