C Xml Serialize List
C# Serialize an object with a list of objects in it. Ask Question Asked 5 years, 9 months ago. XML Serialize generic list of serializable objects.
- 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.
- Feb 06, 2016 How to serialize a list of objects using the XML Serializer in C#. How to serialize a list of objects using the XML Serializer in C#. How to serialize objects to XML - Duration.
Given the following XML:
And the following class:
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.
7 Answers
Marc Gravell♦Marc GravellIf you decorate the User
class with the XmlType
to match the required capitalization:
Then the XmlRootAttribute
on the XmlSerializer
ctor can provide the desired root and allow direct reading into List<>:
...
Credit: based on answer from YK1.
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().
CoincoinCoincoinI 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,
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.
JaredParJaredParHow about
Not particularly fancy but it should work.