How to add many attribute elements in same element?

I want to add many elements with some attributes in same element. Here is my code,

XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("ABC");
doc.AppendChild(root);
for (int i = 0; i < 3; i++)
{
    XmlElement anotherid;
    XmlElement id;
    id = doc.CreateElement("DEF");
    anotherid = doc.CreateElement("GEH");
    anotherid.SetAttribute("Name", "");
    anotherid.SetAttribute("Button", "");
    root.AppendChild(id);
    id.AppendChild(anotherid);

}
doc.Save(@"C:\dummyxml.xml");

It gives output like this following:

<ABC>
  <DEF>
    <GEH Name="" Button="" />
  </DEF>
  <DEF>
    <GEH Name="" Button="" />
  </DEF>
  <DEF>
    <GEH Name="" Button="" />
  </DEF>
</ABC>

But I want output like

   <ABC>
      <DEF>
        <GEH Name="" Button="" />
        <GEH Name="" Button=""/>
        <GEH Name="" Button=""/>
      </DEF>
    </ABC>

please don't neglect for loop. I want output with for loop only. Please guide me. Thanks in advance.

Jon Skeet
people
quotationmark

Well basically the for loop should only contain the creation of the GEH element. You can move the creation of the DEF element outside the loop...

However, I'd also strongly recommend using LINQ to XML rather than the old XmlDocument API... it's much simpler. In this case, the code would look like this:

var doc = new XDocument(
    new XElement("ABC",
        new XElement("DEF",
            Enumerable.Range(1, 3)
                      .Select(ignored => new XElement("GEH",
                           new XAttribute("Name", ""),
                           new XAttribute("Button", "")
                      )
        )
    )
);

people

See more on this question at Stackoverflow