XmlSerializer and List
The XmlSerializer
class offers a straightforward method for deserializing XML data into various data types, including lists of custom objects. This guide demonstrates two approaches to achieve this.
Method 1: Utilizing a Wrapper Class
To deserialize XML into a List<User>
, a wrapper class is necessary to serve as the root element within the XML structure. Consider the UserList
class:
<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>
This class encapsulates a list of User
objects. The [XmlRoot("user_list")]
attribute designates "user_list" as the root element in the XML. The [XmlElement("user")]
attribute maps each User
object to a "user" element.
Next, define the User
class:
<code class="language-csharp">public class User { [XmlElement("id")] public Int32 Id { get; set; } [XmlElement("name")] public String Name { get; set; } }</code>
Finally, use XmlSerializer
for deserialization:
<code class="language-csharp">XmlSerializer serializer = new XmlSerializer(typeof(UserList)); UserList userList = (UserList)serializer.Deserialize(streamOrStringReader);</code>
Replace streamOrStringReader
with your Stream
or StringReader
object containing the XML data.
Method 2: Direct Array Deserialization
Alternatively, you can embed the list directly within the User
class, simplifying the process:
<code class="language-csharp">[XmlRoot("user_list")] public class User { public User[] Items { get; set; } }</code>
Deserialization then becomes:
<code class="language-csharp">XmlSerializer serializer = new XmlSerializer(typeof(User)); User userArray = (User)serializer.Deserialize(streamOrStringReader);</code>
The Items
property now holds an array of User
objects.
Choosing the Right Method
The wrapper class approach (Method 1) provides greater flexibility, while the direct array method (Method 2) offers a more concise solution. The best choice depends on the specific structure of your XML data and personal preference.
The above is the detailed content of How to Deserialize XML into a List Using XmlSerializer?. For more information, please follow other related articles on the PHP Chinese website!