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

Can XmlSerializer Deserialize XML into a List?

Linda Hamilton
Release: 2025-01-13 09:11:44
Original
753 people have browsed it

Can XmlSerializer Deserialize XML into a List?

XmlSerializer and List Deserialization

Can XmlSerializer deserialize XML data directly into a List<T>? Let's examine this with a sample XML structure and a corresponding C# class.

Example XML:

<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

C# User Class:

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

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

Direct deserialization into List<User> isn't directly supported by XmlSerializer. However, a simple workaround achieves this.

Solution: Wrapping the List

The solution involves creating a wrapper class that contains the List<User>:

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

[XmlRoot("user_list")]
public class UserListWrapper
{
    public UserListWrapper() { Users = new List<User>(); }
    [XmlElement("user")]
    public List<User> Users { get; set; }
}</code>
Copy after login

By using this UserListWrapper class, deserialization becomes straightforward. The XmlSerializer will populate the Users list within the wrapper. After deserialization, you can then access the List<User> from the wrapper's Users property. An array (User[]) could also be used instead of the list within the wrapper class, depending on your preference.

The above is the detailed content of Can XmlSerializer Deserialize XML into a List?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template