C# XML deserialization to object list
In some cases, you may need to deserialize XML into a structured data format, such as a list of objects. This article explores the possibilities and necessary steps to achieve this specific deserialization.
Suppose the following XML needs to be converted to List<User>
:
<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>
To implement this conversion you can use the XmlSerializer
class. However, in order to adapt to the structure of XML, it needs to be slightly modified. Instead of deserializing directly to List<User>
, use an intermediate class that contains a list.
The following is an example implementation of a wrapper 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>
With the UserList
class, the deserialization process becomes very simple:
<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>
This extended list serialization provides a cleaner and more general method for deserializing XML into a hierarchical structure.
The above is the detailed content of How to Deserialize XML into a List of Objects in C#?. For more information, please follow other related articles on the PHP Chinese website!