Use XmlSerializer to deserialize XML into a list
Serialization is a powerful technique for converting objects into a stream of data that can be stored or transmitted. A common use case is deserialization, where data is converted back into objects based on a specific data format (such as XML).
Can XmlSerializer convert XML to a list?
Yes, it is possible to use the XmlSerializer class to deserialize XML into a List
Create a wrapper class
To encapsulate the user list, create a wrapper class named UserList:
<code class="language-csharp">[XmlRoot("user_list")] public class UserList { public UserList() { Items = new List<User>(); } [XmlElement("user")] public List<User> Items { get; set; } }</code>
Example
Given the provided XML and User class, here is how to deserialize XML into a List
<code class="language-csharp">XmlSerializer ser = new XmlSerializer(typeof(UserList)); UserList list = new UserList(); list.Items.Add(new User { Id = 1, Name = "abc" }); list.Items.Add(new User { Id = 2, Name = "def" }); list.Items.Add(new User { Id = 3, Name = "ghi" }); ser.Serialize(Console.Out, list);</code>
The above is the detailed content of Can XmlSerializer Deserialize XML Data into a List?. For more information, please follow other related articles on the PHP Chinese website!