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.
Active1 year, 2 months ago

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.

Daniel Schaffer
Daniel SchafferDaniel Schaffer
34.1k27 gold badges104 silver badges153 bronze badges

7 Answers

Marc GravellMarc GravellString
825k213 gold badges2228 silver badges2624 bronze badges
Serialize

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

Community
richauxrichaux
1,9722 gold badges28 silver badges35 bronze badges

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().

CoincoinCoincoin
22.3k7 gold badges46 silver badges71 bronze badges

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.

tudor.iliescutudor.iliescu

Yes, it does deserialize to List<>. No need to keep it in an array and wrap/encapsulate it in a list.

Deserializing code,

NemoNemo

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.

JaredParJaredPar
605k127 gold badges1110 silver badges1369 bronze badges

How about

Not particularly fancy but it should work.

PRJPRJ

C# Serialize Xml To Object

Not the answer you're looking for? Browse other questions tagged c#serializationxml-serializationxml-deserialization or ask your own question.