tags:

views:

892

answers:

3

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.

+2  A: 

What's wrong with the simple Add method?

BFree
I'm guessing the author wants a LINQ solution to this problem, except there doesn't seem to be one. Actually, this is an interesting problem - how to turn an `IEnumerable` into a suitable parameter list =)
Dmitri Nesteruk
+1  A: 

If I'm not mistaken, you should be able to use XDocument.Add():

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.Add(xelement);
}
Dustin Campbell
When I use that code I get "this would create a falsely structured XML document", I tried replacing the variables with "tests" and "test" but same error.
Edward Tanguay
+4  A: 

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")
        ))
    )
);
Jimmy
very slick, thanks!
Edward Tanguay