XmlSerializer and List
Can XmlSerializer
deserialize XML data directly into a List<T>
? Let's examine this with a sample XML structure and a corresponding C# class.
Example XML:
<code class="language-xml"><?xml version="1.0"?> <user_list> <user> <id>1</id> <name>Joe</name> </user> <user> <id>2</id> <name>John</name> </user> </user_list></code>
C# User Class:
<code class="language-csharp">public class User { [XmlElement("id")] public Int32 Id { get; set; } [XmlElement("name")] public String Name { get; set; } }</code>
Direct deserialization into List<User>
isn't directly supported by XmlSerializer
. However, a simple workaround achieves this.
Solution: Wrapping the List
The solution involves creating a wrapper class that contains the List<User>
:
<code class="language-csharp">using System; using System.Collections.Generic; using System.Xml.Serialization; [XmlRoot("user_list")] public class UserListWrapper { public UserListWrapper() { Users = new List<User>(); } [XmlElement("user")] public List<User> Users { get; set; } }</code>
By using this UserListWrapper
class, deserialization becomes straightforward. The XmlSerializer
will populate the Users
list within the wrapper. After deserialization, you can then access the List<User>
from the wrapper's Users
property. An array (User[]
) could also be used instead of the list within the wrapper class, depending on your preference.
The above is the detailed content of Can XmlSerializer Deserialize XML into a List?. For more information, please follow other related articles on the PHP Chinese website!