Using Linq, how to parse Xml to C# objects which only accept parameters in the constructor?
c#, linq, xml
Solution
You don't need any anonymous objects at all. Using LINQ to XML you can simply select User nodes from your XML and create actual `User` class instances by invoking constructor with values selected from XML node:
// xml contains XML string, like in your sample
var document = XDocument.Parse(xml);
var users = document.Descendants("User")
.Select(u => new User(
u.Element("Name").Value,
u.Element("Gender").Value,
u.Element("ImageUrl").Value
));
Problem
Suppose I have some XML Like this: ``` <User> <Name>X</Name> <Gender>Y</Gender> <ImageUrl>Z</ImageUrl> </User> ``` and I have a class called User. ``` public class User { public User(string name, string gender, string imageUrl) { Name = name; Gender = gender; ImageUrl = imageUrl; } public string Name { get; } public string Gender { get; } public string ImageUrl { get; } } ``` which accepts a constructor `public User(string name, string gender, string ImageUrl)` only and does not allow set for the properties, what is the best way to parse this xml into these objects using linq and c#? In a crude way, it is possible to create anonymous objects and then iterate over them to create the required objects. Is there a more efficient way to do this?