Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to convert an IEnumerable into a collection of XElements?

Tags:

c#

xml

linq

I'm trying to persist an XML file to disk using LINQ. I have a class of business objects including collections of strings (List) that I want to convert into XML. Is there a simple, one liner to convert this list into a list of XML Elements?

For example, my list may be:

List<string> collection = new List<string>() {"1", "2", "3"}

The output should be:

<Collection>
     <Element>1</Element>
     <Element>2</Element>
     <Element>3</Element>
</Collection>

At the moment, I'm using this sort of syntax:

XElement Configuration =
    new XElement("Configuration",
    new XElement("Collection",  collection.ToArray()
    ),
);

However, this concatenates the collection into a a single string element.

like image 934
DaEagle Avatar asked Dec 18 '22 09:12

DaEagle


1 Answers

XElement Configuration = new XElement("Collection",
      collection.Select(c=>new XElement("Element", c)));
like image 59
mmx Avatar answered Dec 19 '22 22:12

mmx