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.
Yes, it will serialize and deserialize a List<>. Just make sure you use the [XmlArray] attribute if in doubt.
This works with both Serialize() and Deserialize().
Not sure about List<T> but Arrays are certainly do-able. And a little bit of magic makes it really easy to get to a List again.
How about
Not particularly fancy but it should work.
I think I have found a better way. You don't have to put attributes into your classes. I've made two methods for serialization and deserialization which take generic list as parameter.
Take a look (it works for me):
So you can serialize whatever list you want! You don't need to specify the list type every time.
Yes, it does deserialize to List<>. No need to keep it in an array and wrap/encapsulate it in a list.
Deserializing code,
If you decorate the
User
class with theXmlType
to match the required capitalization:Then the
XmlRootAttribute
on theXmlSerializer
ctor can provide the desired root and allow direct reading into List<>:...
Credit: based on answer from YK1.