views:

32

answers:

2

The inverse question of How can I transform XML into a List or String[]?.

I have a List<string> of users and want to convert them to the following xml :

<Users>
    <User>Domain\Alice</User>
    <User>Domain\Bob</User>
    <User>Domain\Charly</User>
</Users>

I am currently wrapping this list in a class and use XmlSerializer to solve this but I find this quite heavy ...

So is there a more straightforward solution using Linq to Xml ?

+1  A: 
XElement xml = new XElement("Users",
                    (from str in aList select new XElement("User", str)).ToArray());

This might do it. Not sure if the .ToArray is necessary.

Joachim VR
Exactly what I was looking for :) Thanks a lot. It works fine without the .ToArray()
hoang
A: 
        List<User> list = new List<User>();
        list.Add(new User { Name = "Domain\\Alice" });
        list.Add(new User { Name = "Domain\\Bob" });
        list.Add(new User { Name = "Domain\\Charly" });

        XElement users = new XElement("Users");
        list.ForEach(user => { users.Add(new XElement("User", user.Name)); });

        Console.WriteLine(users);
jmservera
Thanks ! It works but you are still wrapping the data to a new class, which I was trying to avoid.
hoang