Search code examples
c#asp.netxmliterationxelement

How can I add XElement iterating elements?


This is my code:

var xml = new XElement("test", new[] {
    new XElement("group", new[] {
        new XElement("date", dateNow.ToString("dd/MM/yyyy HH:mm:ss"))
    }),

    new XElement("users", new[] {
        foreach(var item in in PlaceHolderCustom.Controls)
        {
            new XElement("nome", ((TextBox)item.FindControl("myTextBox")).Text)
        }
    })
});

I'd like to set in the xml some fixed fields (within the element "group") and some that would iterate across a placeholder. But the syntax seems to be wrong when I try to add a new "iterating" list.

Where am I wrong?


Solution

  • Use linq .Select to perform the foreach. Also when you create the array the new [] {} syntax is valid only for new string[]. In your case use:

    • new XElement[] {}
    • Or because the method gets a params object[] you can just give each new XElement independently without wrapping with an array

    So showing both ways of passing the collection of XElements:

    var xml = new XElement("test",
        new XElement("group", new XElement[] {
            new XElement("date", dateNow.ToString("dd/MM/yyyy HH:mm:ss"))
        }),
        new XElement("users", PlaceHolderCustom.Control.Select(item =>
            new XElement("nome", ((TextBox)item.FindControl("myTextBox")).Text)).ToArray())
    );