How to build an XDocument with a foreach and LINQ?

c#, linq, xml

Solution

You need a root element.

var xdoc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement("Root",
        _dataTypes.Select(datatype => new XElement(datatype._pluralCamelNotation,
            new XElement(datatype._singlarCamelNotation),
            new XElement("id", "1"),
            new XElement("whenCreated", "2008-12-31")
        ))
    )
);

Problem

I can use XDocument to build the following file which works fine: ``` XDocument xdoc = new XDocument ( new XDeclaration("1.0", "utf-8", null), new XElement(_pluralCamelNotation, new XElement(_singularCamelNotation, new XElement("id", "1"), new XElement("whenCreated", "2008-12-31") ), new XElement(_singularCamelNotation, new XElement("id", "2"), new XElement("whenCreated", "2008-12-31") ) ) ); ``` However, I need to build the XML file by iterating through a collection like this: ``` XDocument xdoc = new XDocument ( new XDeclaration("1.0", "utf-8", null)); foreach (DataType dataType in _dataTypes) { XElement xelement = new XElement(_pluralCamelNotation, new XElement(_singularCamelNotation, new XElement("id", "1"), new XElement("whenCreated", "2008-12-31") )); xdoc.AddInterally(xelement); //PSEUDO-CODE } ``` There is Add, AddFirst, AddAfterSelf, AddBeforeSelf, but I could get none of them to work in this context. Is an iteration with LINQ like this possible? Answer: I took Jimmy's code suggestion with the root tag, changed it up a bit and it was exactly what I was looking for: ``` var xdoc = new XDocument( new XDeclaration("1.0", "utf-8", null), new XElement(_pluralCamelNotation, _dataTypes.Select(datatype => new XElement(_singularCamelNotation, new XElement("id", "1"), new XElement("whenCreated", "2008-12-31") )) ) ); ``` Marc Gravell posted a better answer to this on this StackOverflow question.

Original source

Related problems