Thursday, March 24, 2011

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

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.

From stackoverflow
  • XElement Configuration = new XElement("Collection",
          collection.Select(c=>new XElement("Element", c)));
    

0 comments:

Post a Comment