How to convert List <string> to XML using Linq?

Reverse Question How to convert XML to a list or string []? .

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

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

Currently, I am moving this list to a class and am using it XmlSerializerto solve this problem, but I find it quite heavy ...

So, is there a simpler solution using Linq to Xml?

+3
source share
2 answers
XElement xml = new XElement("Users",
                    (from str in aList select new XElement("User", str)).ToArray());

It can do it. Not sure if .ToArray is needed.

+1
source
        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);
0
source

Source: https://habr.com/ru/post/1768217/


All Articles