How to write an XML file with a for loop?

I am trying to do a quick program that creates a very simple XML file. I want to create an XML file that uses a 'for loop' to create a portion of the XML several times. When I build I get an error saying " Invalid expression term 'for'. I check my parenthesis balance and it does seem to check out.

Does anyone know what this error means?

    static void Main(string[] args)
    { 
        XDocument myDoc = new XDocument(
        new XDeclaration("1.0" ,"utf-8","yes"),
        new XElement("Start"),

        for(int i = 0; i <= 5; i++)
        {
                         new XElement("Entry", 
                             new XAttribute("Address", "0123"),
                             new XAttribute("default", "0"),

                        new XElement("Descripion", "here is the description"),

                        new XElement("Data", "Data goes here ")

                );

            }
        );

        }
Jon Skeet
people
quotationmark

You're currently trying to use a for loop in the middle of a statement. That's not going to work.

Options:

  • Use Enumerable.Range to create a range of values, and then transform that using Select:

    XDocument myDoc = new XDocument(
        new XDeclaration("1.0" ,"utf-8","yes"),
        // Note that the extra elements are *within* the Start element
        new XElement("Start",
            Enumerable.Range(0, 6)
                      .Select(i => 
                           new XElement("Entry", 
                               new XAttribute("Address", "0123"),
                               new XAttribute("default", "0"),
                               new XElement("Descripion", "here is the description"),
                               new XElement("Data", "Data goes here ")))
    );
    
  • Create the document first, and add the elements in a loop

    XDocument myDoc = new XDocument(
        new XDeclaration("1.0" ,"utf-8","yes"),
        new XElement("Start"));
    for (int i = 0; i <= 5; i++) 
    {
        myDoc.Root.Add(new XElement("Entry",
                           new XAttribute("Address", "0123"),
                           new XAttribute("default", "0"),
                           new XElement("Descripion", "here is the description"),
                           new XElement("Data", "Data goes here "));
    }
    

people

See more on this question at Stackoverflow