Home >Backend Development >C++ >How to Deserialize XML into a List using C#?

How to Deserialize XML into a List using C#?

DDD
DDDOriginal
2025-01-13 08:18:42782browse

How to Deserialize XML into a List using C#?

Deserialize XML to List using additional class wrapper

You can use XmlSerializer to deserialize XML to List<T> by using an additional class to encapsulate the list.

Packaging class

Create a class that encapsulates a list, for example:

<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>

User class

Define the User class as before:

<code class="language-csharp">public class User
{
    [XmlElement("id")]
    public Int32 Id { get; set; }

    [XmlElement("name")]
    public String Name { get; set; }
}</code>

Deserialization code

Deserialize the XML using the following code:

<code class="language-csharp">using System.Xml.Serialization;

XmlSerializer ser = new XmlSerializer(typeof(UserList));
UserList list = (UserList)ser.Deserialize(new XmlTextReader("users.xml"));</code>

This will deserialize the XML into a UserList class, which contains a list of User objects.

The above is the detailed content of How to Deserialize XML into a List using C#?. 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