Tutorial :How to build an XDocument with a foreach and LINQ?



Question:

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.


Solution:1

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")          ))      )  );  


Solution:2

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);  }  


Solution:3

I know it's very very old post but I stumbled across this today trying to solve the same problem. You have to add the element to the Root of the document:

xdoc.Root.Add(xelement);  


Solution:4

What's wrong with the simple Add method?


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »