3

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 ?

Community
  • 1
  • 1
hoang
  • 1,887
  • 1
  • 24
  • 34

2 Answers2

1
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
  • 2,320
  • 1
  • 15
  • 24
0
        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
  • 6,454
  • 2
  • 32
  • 45
  • Thanks ! It works but you are still wrapping the data to a new class, which I was trying to avoid. – hoang Oct 06 '10 at 12:24