Home > Backend Development > C++ > How to Deserialize XML into a List of Objects in C#?

How to Deserialize XML into a List of Objects in C#?

DDD
Release: 2025-01-13 08:13:46
Original
462 people have browsed it

How to Deserialize XML into a List of Objects in C#?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template