Back to all posts
C#.NETXML

How to Convert Dictionary List to XElement

SathishMarch 12, 2010

Converting collections to XML is a common requirement. Here's how to convert Dictionary and List to XElement in C#.

Dictionary to XElement

csharp
using System.Xml.Linq;
using System.Collections.Generic;

public static XElement DictionaryToXElement(Dictionary<string, string> dict, string rootName)
{
    return new XElement(rootName,
        dict.Select(kvp => new XElement(kvp.Key, kvp.Value))
    );
}

// Usage
var dict = new Dictionary<string, string>
{
    { "Name", "John" },
    { "Email", "[email protected]" },
    { "City", "Sydney" }
};

XElement xml = DictionaryToXElement(dict, "Person");

List to XElement

csharp
public static XElement ListToXElement<T>(List<T> list, string rootName, string itemName)
{
    return new XElement(rootName,
        list.Select(item => new XElement(itemName, item))
    );
}

// Usage
var list = new List<string> { "Apple", "Banana", "Cherry" };
XElement xml = ListToXElement(list, "Fruits", "Fruit");

Output

xml
<Person>
  <Name>John</Name>
  <Email>[email protected]</Email>
  <City>Sydney</City>
</Person>
0claps
Share this post

Comments

Protected by reCAPTCHA v3

No comments yet. Be the first to comment.