LINQ to XML: Convert a List into a Set of XElements


I ran into the situation today where I had a List of integer Ids that I needed to turn into an XML string. I thought about using the XmlWriter class but felt it was a bit overkill as it was a very simple XML string I was trying to generate. My next thought was to just iterate through the Ids and generate the XML manually, something like the following:

List<int> ids = new List<int>() { 1, 2, 3, 4, 5 };

StringBuilder xml = new StringBuilder();
xml.Append("<Ids>");

foreach(int id in ids)
     xml.Append("<Id>" + id + "</Id>");

xml.Append("</Ids>");

Console.Write(xml.ToString());

// Result
// ------
// <Ids>
//     <Id>1</Id>
//     <Id>2</Id>
//     <Id>3</Id>
//     <Id>4</Id>
//     <Id>5</Id>
// </Ids>

While the above solution worked, I was wondering if there was something in the LINQ to XML classes that I could use to perform this operation in a more compact way. After some research it turns out there is a very elegant way of doing this. The single statement below creates a new XElement object with a single node named Ids and as that node’s content is passed a collection of XElement objects, one for each Id in the list.

List<int> ids = new List<int>() { 1, 2, 3, 4, 5 };

XElement xmlIds = new XElement("Ids", ids.Select(i => new XElement("Id", i)));

Console.Write(xmlIds.ToString());

// Result
// ------
// <Ids>
//     <Id>1</Id>
//     <Id>2</Id>
//     <Id>3</Id>
//     <Id>4</Id>
//     <Id>5</Id>
// </Ids>

This technique is very useful if you are using a LINQ to SQL DataContext which contains a stored procedure that accepts an XML string as a parameter as when calling that stored procedure from your DataContext, you are required to pass in an XElement not just an XML string.

Advertisements
Posted in LINQ. Tags: , . 2 Comments »

2 Responses to “LINQ to XML: Convert a List into a Set of XElements”

  1. Praveen J Says:

    Thanks Nick, very informative post.

    Here is a way for adding attributes to the XElements.
    XElement xmlElements = new XElement(“Branches”, Branches.Select(i => new XElement(“branch”, new XAttribute(“id”, i))));

    output:

  2. Convert a List of items to an XElement in C# | Yasser Shaikh Says:

    […] XElement.Parse() and StringBuilder to create an XElement of a required type. Today I came across this post on some blog and then this thread on stackoverflow. Below are the most efficient ways of doing the same. Hope […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: