Home >Backend Development >C++ >Can XmlSerializer Deserialize XML Data into a List?

Can XmlSerializer Deserialize XML Data into a List?

Barbara Streisand
Barbara StreisandOriginal
2025-01-13 08:08:42358browse

Can XmlSerializer Deserialize XML Data into a List?

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. However, since the XmlSerializer usually converts XML into a direct instance of a class, slight modification is required to achieve this.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn