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 ?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for :) Thanks a lot. It works fine without the .ToArray()
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);

1 Comment

Thanks ! It works but you are still wrapping the data to a new class, which I was trying to avoid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.