Deserialize XML to List using additional class wrapper
You can use XmlSerializer
to deserialize XML to List<T>
by using an additional class to encapsulate the list.
Packaging class
Create a class that encapsulates a list, for example:
[XmlRoot("user_list")] public class UserList { public UserList() { Items = new List<User>(); } [XmlElement("user")] public List<User> Items { get; set; } }
User class
Define the User
class as before:
public class User { [XmlElement("id")] public Int32 Id { get; set; } [XmlElement("name")] public String Name { get; set; } }
Deserialization code
Deserialize the XML using the following code:
using System.Xml.Serialization; XmlSerializer ser = new XmlSerializer(typeof(UserList)); UserList list = (UserList)ser.Deserialize(new XmlTextReader("users.xml"));
This will deserialize the XML into a UserList
class, which contains a list of User
objects.
The above is the detailed content of How to Deserialize XML into a List using C#?. For more information, please follow other related articles on the PHP Chinese website!