Serialize object graph to XML in .Net

How to serialize any data structure to XML? My first idea was XmlSerializer. But then I found out it had some serious drawbacks. Luckily, there is a better option - NetDataContractSerializer.

In .Net, there are a few classes for (de)serialization. This is an overview of their features:


  • Cannot serialize circular references.
  • If more objects point to the same object, its copies are created in the xml for each of these references.
  • Has to know all types that could be encountered during serialization in advance - throws an exception on unknown type. Known types are passed in the constructor to XmlSerializer or marked by XmlIncludeAttribute.
  • Generates simple readable xml.

  • Has to know types in advance - like XmlSerializer.
  • Can serialize circular references - construct with preserveObjectReferences = true
  • Used by WCF.
NetDataContractSerializer - better!
  • Serializes object graph properly including circular references.
  • Doesn't have to know types in advance.
  • However, MSDN states that it can be only used in .Net <-> .Net communication, which is ok also for storing object in a file.
  • Generates simple readable xml.
  • Works well, like NetDataContractSerializer.
  • Disadvantage is that it serializes to binary format, which make its unusable e.g. for saving to a file that user could later edit.
  • The output is smallest thanks to the binary format.
  • Deprecated. Cannot serialize generic collections
- All serializers need the type to be serialized marked by SerializableAttribute.

kick it on

What does it mean that XmlSerializer has to know all types that could be encountered during serialization in advance?
Imagine that we have two classes: Base and Derived.


public class Base


public string name;

public Base()


name = "base instance";




public class Derived : Base


public Derived left;

public Derived right;

public Derived()




What if we have a reference to Base and we actually don't want to care about the actual type?

Base b = new Derived();

// we only know we are holding reference to Base

// and we don't want to care about the actual type

XmlSerializer ser = new XmlSerializer(typeof(Base));

// serialize

using (FileStream fs = File.Create(AppDomain.CurrentDomain.BaseDirectory + "data.xml"))


// XmlSerializer throws an Exception

ser.Serialize(fs, b);


// deserialize

using (FileStream fs = File.OpenRead(AppDomain.CurrentDomain.BaseDirectory + "data.xml"))


Base baseDeserialized = (Base)ser.Deserialize(fs);

Derived deserialize = baseDeserialized as Derived;


XmlSerializer throws an exception, because it encounters an "unknown" type - Derived. We could solve this by passing all the possible derived types in constructor of XmlSerializer or tagging all by XmlIncludeAttribute. This is of course inconvenient if you have a lot of classes. The worst thing is that when you add a derived class, you have to change code elsewhere.
NetDataContractSerializer doesn't have this problem.

The second issue with XmlSerializer is that it cannot serialize complex object graph. What does it mean "to serialize object graph"?

Derived top = new Derived();

top.left = new Derived(); = "left son";

top.right = new Derived(); = "right son";

top.left.right = new Derived();

// top

// / \

// left right

// \ /

// bottom

top.right.left = top.left.right;

XmlSerializer ser = new XmlSerializer(typeof(Derived));

using (FileStream fs = File.Create(AppDomain.CurrentDomain.BaseDirectory + "data.xml"))


ser.Serialize(fs, top);


using (FileStream fs = File.OpenRead(AppDomain.CurrentDomain.BaseDirectory + "data.xml"))


Derived deserialized = (Derived)ser.Deserialize(fs);

// false - we want true

bool ok = deserialized.left.right == deserialized.right.left;


After deserialization,
deserialized.left.right == deserialized.right.left is false, that means the object graph is different. Worse - XmlSerializer cannot serialize circular references at all.
Again, NetDataContractSerializer doesn't have any of these problems.

kick it on

Posted by Martin Konicek on 10:59 PM


thoward37 said...

Just a short note: This class is only available in Framework versions 3.0 or later. Anyone writing for 2.0 compatability won't be able to take advantage of NetDataContractSerializer.

Inv said...

That is right of course. Thank you!

Anonymous said...

"need the type to be serialized marked by SerializableAttribute" - Only BinaryFormatter and SoapFormatter have this restriction. (Note that these serializers only serialize private data, and you have no control over the format). These two formatters also include .NET type information.

XmlSerializer does not need any attributes at all by default. (Note it only serializes public data.) It does not include .NET information (so you need to provide types).

Also, it is possible to initialize XmlSerializer with SoapReflectionImporter, which does allow complex object graphs (even circular references); this has been available since .NET 1.0, so is an option if you don't have the newer frameworks.

There is also an optional IXmlSerializable interface that works with XmlSerializer for precise custom control over formatting.

DataContractSerializer and NetDataContractSerializer try to be inclusive of the older formats. The have their own DataContractAttribute which allows either public or private data to be serialized (with the DataMemberAttribute).

DCS and NDCS also recognize the older SerializableAttribute (so classes can port across) and the latest version (3.5) also automatically works even with no attributes (like XmlSerializer).

DCS and NDCS both are closely related and meant to replace the older serialization (DCS for XmlSerializer and NDCS, with .NET type information, for BinaryFormatter/SoapFormatter).

In some cases you will still see XmlSerializer used as it is more flexible than DCS. (WCF defaults to DCS but will automatically switch to XmlSerializer if necessary).

dot net training said...

Your article was really informative and conveys whole concept in detail. Thanks for sharing..

jack wilson said...

Thank You for Sharing Valuable Information. I like this blog and this is very informative.

Dot Net Training Chennai

dhanamlakshmi palu said...

Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing. PHP Training in chennai | PHP Training chennai | PHP course in chennai | PHP course chennai

Melisa said...

This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.
PHP Training Center in Chennai|php training in velachery

varshini devi said...

Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing dude.
Web design training Chennai|Salesforce training institute in Chennai|Web design course in Chennai

Melisa said...

Thanks for sharing this niche useful informative post to our knowledge, Actually SAP is ERP software that can be used in many companies for their day to day business activities it has great scope in future so do your SAP training in chennai
SAP Institutes in Chennai|sap training center in Chennai|SAP ABAP Training in Chennai

jhansi joe said...

Well post, Thanks for sharing this to our vision. In recent day’s customer relationship play vital role to get good platform in business industry, Sales force crm tool helps you to maintain your customer relationship enhancement.
Salesforce course in Chennai|Salesforce training chennai|Salesforce training institutes in Chennai|Salesforce training in Chennai

jhansi joe said...

Helo Admin,
Awesome Post! I like writing style, how you describing the topics throughout the post. I hope many web reader will keep reading your post at the end, Thanks for sharing your view.
cognos Training in Chennai|cognos Certification|Best COGNOS Training Institute in Chennai

varshini devi said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
Python Training in Chennai|Python Courses in Chennai|Python Classes in Chennai

Savitha said...

Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
Oracle Training In Chennai

Leslie Lim said...

Man I love this site. It is just so awesome. Whatever you want, all are available here.

Tech Fizy said...

Thanks for sharing informative article. Download Windows 7 ultimate for free from getintopc. It helps you to explore full functionality of windows operating system.

vijay antony said...

Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals

Best Java Training Institute Chennai

Careen joseph said...

I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
Best Hadoop Training Institute In chennai


johnsy sai said...

The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
Digital Marketing Training in Chennai

Digital Marketing Training in Bangalore

digital marketing training in tambaram

digital marketing training in annanagar

gowsalya said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
full stack developer training in annanagar

full stack developer training in tambaram

full stack developer training in velachery

Mouni yoga said...

This is a nice post in an interesting line of content.Thanks for sharing this article, great way of bring this topic to discussion.
python training institute in chennai
python training in Bangalore
python training institute in chennai

ummi ari said...

Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.

Blueprism training in Chennai

Blueprism training in Bangalore

nivatha said...

Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging

Data Science training in Chennai
Data science training in bangalore
Data science online training
Data science training in pune

Rohil singh said...

Great post and informative was awesome to read, thanks for sharing this great content to my vision.
Good discussion.
Six Sigma Training in Abu Dhabi
Six Sigma Training in Dammam
Six Sigma Training in Riyadh

sudha P said...

Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
java training in chennai

java training in marathahalli | java training in btm layout

johnsy sai said...

Nice post. By reading your blog, i get inspired and this provides some useful information. Thank you for posting this exclusive post for our vision. 
advanced excel training in bangalore

Chitra devi said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 

best rpa training in chennai |
rpa training in chennai | rpa online training |
rpa training in chennai |
rpa training in bangalore
rpa training in pune
rpa training in marathahalli
rpa training in btm

ijazz jazz said...

Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

AWS Training in Bangalore | Amazon Web Services Training in bangalore , india

AWS Training in pune | Amazon Web Services Training in Pune, india

AWS Training in Chennai|Amazon Web Services Training in Chennai,India

aws online training and certification | amazon web services online training ,india

kevin john said...

Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information.

best rpa training in chennai
rpa training in chennai |
rpa online training
rpa course in bangalore
rpa training in pune
rpa training in marathahalli
rpa training in btm

Mouni yoga said...

Great thoughts you got there, believe I may possibly try just some of it throughout my daily life.
python course in pune | python course in chennai | python course in Bangalore

jeeva said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.

best rpa training in chennai
rpa training in chennai |
rpa online training
rpa course in bangalore
rpa training in pune
rpa interview questions and answers | blueprism interview questions and answers

gowthunan said...

My rather long internet look up has at the end of the day been compensated with pleasant insight to talk about with my family and friends.
safety course in chennai

sathya shri said...

I am a regular reader of your blog and being students it is great to read that your responsibilities have not prevented you from continuing your study and other activities. Love
angularjs Training in bangalore

angularjs Training in bangalore

angularjs online Training

angularjs Training in marathahalli

angularjs interview questions and answers

Anand said...

Thanks for your informative article, Your post helped me to understand the future and career prospects & Keep on updating your blog with such awesome article.

Java Training in Chennai
Python Training in Chennai
IOT Training in Chennai
Selenium Training in Chennai
Data Science Training in Chennai
FSD Training in Chennai
MEAN Stack Training in Chennai

Bee Yes said...

Amazing Article ! I have bookmarked this article page as i received good information from this. All the best for the upcoming articles. I will be waiting for your new articles. Thank You ! Kindly Visit Us @ Coimbatore Travels | Ooty Travels | Coimbatore Airport Taxi | Coimbatore taxi

Deepika Analy said...

Thanks for making me this article. You have done a great job by sharing this content in here. Keep writing article like this.

Cloud Training
Cloud Training in Chennai
Cloud Training in OMR
Cloud Training in Velachery
Cloud Training in Thiruvanmiyur

ProPlus Academy said...

Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
digital marketing course in coimbatore
php training in coimbatore

gowthunan said...

Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.
safety course in chennai

Post a Comment