Search code examples
asp.net-mvc-4foreachlinq-to-xmlxelement

Using Linq to XML foreach to create muliple XElements


I'm building an XML file dynamically using new XElement(), and midway through the file creation I need to iterate over a set of child records and create XElements for them. The problem I'm having is that I need to create more than 1 XElement per iteration. This is a my loop:

from t in trans.SalesTransactionLines
select new XElement("text", new XAttribute("lang", "en"), t.ItemName)

This works fine, but I need an additional 'position' XElement before each 'text' Element. This is the kind of thing I want, which doesn't work:

from t in trans.SalesTransactionLines
select new XElement("position",new XAttribute("x", "40"), new XAttribute("y", "420")),
new XElement("text", new XAttribute("lang", "en"), t.ItemName)

This is the result I'm looking for:

<position x="40" y="420" />
<text>Fender Classic Strat 70s Natural RN</text>
<position x="40" y="420" />
<text>Fender Classic 50s Tele White Blonde</text>

Solution

  • Use method based syntax and SelectMany method instead:

    trans.SalesTransactionLines.SelectMany(x => new[] {
                                                    new XElement("position",
                                                        new XAttribute("x", "40"),
                                                        new XAttribute("y", 420")),
                                                    new XElement("text",
                                                        new XAttribute("lang", "en"),
                                                        x.ItemName)
    })