Given the following 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>
And the following class:
public class User { [XmlElement("id")] public Int32 Id { get; set; } [XmlElement("name")] public String Name { get; set; } }
Is it possible to use XmlSerializer
to deserialize the xml into a List<User>
? If so, what type of additional attributes will I need to use, or what additional parameters do I need to use to construct the XmlSerializer
instance?
An array ( User[]
) would be acceptable, if a bit less preferable.
Serialization is the process of converting an object into a form that can be readily transported. For example, you can serialize an object and transport it over the Internet using HTTP between a client and a server. On the other end, deserialization reconstructs the object from the stream.
Remarks. The XmlIgnoreAttribute belongs to a family of attributes that controls how the XmlSerializer serializes or deserializes an object. If you apply the XmlIgnoreAttribute to any member of a class, the XmlSerializer ignores the member when serializing or deserializing an instance of the class.
You can encapsulate the list trivially:
using System; using System.Collections.Generic; using System.Xml.Serialization; [XmlRoot("user_list")] public class UserList { public UserList() {Items = new List<User>();} [XmlElement("user")] public List<User> Items {get;set;} } public class User { [XmlElement("id")] public Int32 Id { get; set; } [XmlElement("name")] public String Name { get; set; } } static class Program { static void Main() { 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); } }
If you decorate the User
class with the XmlType
to match the required capitalization:
[XmlType("user")] public class User { ... }
Then the XmlRootAttribute
on the XmlSerializer
ctor can provide the desired root and allow direct reading into List<>:
// e.g. my test to create a file using (var writer = new FileStream("users.xml", FileMode.Create)) { XmlSerializer ser = new XmlSerializer(typeof(List<User>), new XmlRootAttribute("user_list")); List<User> list = new List<User>(); list.Add(new User { Id = 1, Name = "Joe" }); list.Add(new User { Id = 2, Name = "John" }); list.Add(new User { Id = 3, Name = "June" }); ser.Serialize(writer, list); }
...
// read file List<User> users; using (var reader = new StreamReader("users.xml")) { XmlSerializer deserializer = new XmlSerializer(typeof(List<User>), new XmlRootAttribute("user_list")); users = (List<User>)deserializer.Deserialize(reader); }
Credit: based on answer from YK1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With