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:


XmlSerializer

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

DataContractSerializer
  • 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.
BinarryFormatter
  • 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.
SoapFormatter
  • Deprecated. Cannot serialize generic collections
- All serializers need the type to be serialized marked by SerializableAttribute.

kick it on DotNetKicks.com

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.

[Serializable]

public class Base

{

public string name;

public Base()

{

name = "base instance";

}

}

[Serializable]

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

top.left.name = "left son";

top.right = new Derived();

top.right.name = "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 DotNetKicks.com

Posted by Martin Konicek on 10:59 PM

130 comments:

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.

Martin Konicek 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..

Unknown said...

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

Dot Net Training Chennai

Unknown 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.
regards,
PHP Training Center in Chennai|php training in velachery

Unknown 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.
Regards,
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
Regards,
SAP Institutes in Chennai|sap training center in Chennai|SAP ABAP Training in Chennai

Unknown 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.
Regards,
Salesforce course in Chennai|Salesforce training chennai|Salesforce training institutes in Chennai|Salesforce training in Chennai

Unknown 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.
Regards,
cognos Training in Chennai|cognos Certification|Best COGNOS Training Institute in Chennai

Unknown 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…
Regards,
Python Training in Chennai|Python Courses in Chennai|Python Classes in Chennai

Unknown 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

Unknown said...

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

www.imarksweb.org

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

Unknown 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

Unknown 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

amazon-web-services-training-institute-in-chennai

gowsalya 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

Anonymous 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

Mounika 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

Unknown 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 said...

Great post and informative blog.it 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

Unknown 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

gowsalya 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

Unknown 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

UNKNOWN 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

Unknown 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

Mounika 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

Unknown said...

I am really happy with your blog because your article is very unique and powerful for new reader.
Click here:
selenium training in chennai
selenium training in bangalore
selenium training in Pune
selenium training in pune
Selenium Online Training

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

Unknown 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

DeepikaOrange 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

haripriya said...

All the points you described so beautiful. Every time i read your i blog and i am so surprised that how you can write so well.
Microsoft Azure online training
Selenium online training
Java online training
Java Script online training
Share Point online training

sasitamil said...

Were a gaggle of volunteers as well as starting off a brand new gumption within a community. Your blog furnished us precious details to be effective on. You've got completed any amazing work!

devops online training

aws online training

data science with python online training

data science online training

rpa online training

Jagadeesh said...

Thanks for this article.
Learn Digital Academy  Offers, Digital Marketing Course in Bangalore.
practical coursework to students.

zaintech99 said...

After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
ExcelR Data science courses in Bangalore

Aaditya said...

Awesome blog. Very informative post. Keep up the good work!

ExcelR Data Science

Priyanka said...

Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
python training in bangalore

data science analytics rakshi said...

I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!data science course in dubai

malaysiaexcelr01 said...


Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.

BIG DATA COURSE MALAYSIA

istiaq ahmed said...

A great website with interesting and unique material what else would you need.
Data Science Course in Pune

zaintech99 said...

amazing article of this week thank u so much
top 7 best washing machine

Ajish said...

Nice Post! Thank you for sharing knowledge, it was very good post to update my knowledge and improve my skills. keep blogging.
Java Training in Electronic City

saketh said...

Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading Python training in pune new articles. Keep up the good work!

Priyanka said...

Attend The Digital Marketing courses in bangalore From ExcelR. Practical Digital Marketing courses in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Digital Marketing courses in bangalore.
Digital Marketing Courses in Bangalore

zaintech99 said...

It should be noted that whilst ordering papers for sale at paper writing service, you can get unkind attitude. In case you feel that the bureau is trying to cheat you, don't buy term paper from it.
www.technewworld.in
How to Start A blog 2019
Eid AL ADHA


lucy88 said...

Its as if you had a great grasp on the subject matter, but you forgot to include your readers. Perhaps you should think about this from more than one angle.
Data Science Courses

saketh said...

cool stuff you have and you keep Python training in pune overhaul every one of us

Raji said...

Thanks for posting this highly informative article. I feel glad about learning more about this concept. Maintain the number of posting and keep up the good work!
Data Science Course in Chennai | Data Science Training in Chennai

Priyanka said...

Attend The Data Analytics Course From ExcelR. Practical Data Analytics Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Course.
ExcelR Data Analytics Course

Prwatech said...

I learned World's Trending Technology from certified experts for free of cost. I Got a job in decent Top MNC Company with handsome 14 LPA salary, I have learned the World's Trending Technology from best training institute for data science in bangalore experts who know advanced concepts which can help to solve any type of Real-time issues in the field of Python. Really worth trying Instant Approval Blog Commenting Sites

gautham said...

There are many uses of azure development in cloud development. learn at azure training in hyderabad

ExcelR Pune said...

Really thanks for sharing...This blog is awesome very informative..
ExcelR Machine Learning

online idea lab said...

Thank you for excellent article.You made an article that is interesting.
Best AWS certification training courses. Build your AWS cloud skills with expert instructor- led classes. Live projects, Hands-on training,24/7 support.
https://onlineidealab.com/aws-certification/

Tuhin said...

keep up the good work. this is an Assam post. this to helpful, i have reading here all post. i am impressed. thank you. this is our digital marketing training center. This is an online certificate course
digital marketing training in bangalore / https://www.excelr.com/digital-marketing-training-in-bangalore

Tuhin said...

keep up the good work. this is an Assam post. this to helpful, i have reading here all post. i am impressed. thank you. this is our digital marketing training center. This is an online certificate course
digital marketing training in bangalore | https://www.excelr.com/digital-marketing-training-in-bangalore

imexpert said...

Nice blog! Such a good information about data analytics and its future..
Good post! I must say thanks for the information.
data analytics course L
Data analytics Interview Questions

i Digital Academy said...

Thank You for Sharing this Valuable Information with us...
Digital Marketing Courses in Bangalore

Data Science Course said...

Really awesome blog!!! I finally found a great post here.I really enjoyed reading this article. Thanks for sharing valuable information.
Data Science Course
Data Science Course in Marathahalli
Data Science Course Training in Bangalore

Priyanka said...

Attend The Bangalore Digital Marketing Course From ExcelR. Practical Bangalore Digital Marketing Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Bangalore Digital Marketing Course.
Bangalore Digital Marketing Course

priyash said...

wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries.
Data science Interview Questions

datasciencecourse said...

I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!

Digital marketing courses in Bangalore

priyash said...

Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance

divya said...

Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.thanks a lot.
Ai & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai

datasciencecourse said...

After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.

Simple Linear Regression

Correlation vs Covariance

Jayalakshmi said...

Thanks of sharing this post…Python is the fastest growing language that helps to get your dream job in a developing area. It says every fundamental in a programming, so if you want to become an expertise in python get some training





Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery

Priyanka said...

Attend The Data Science Training Bangalore From ExcelR. Practical Data Science Training Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Science Training Bangalore.
Data Science Training Bangalore

priyash said...

Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple linear regression
data science interview questions

datasciencecourse said...

I am looking for and I love to post a comment that "The content of your post is awesome" Great work!

data science interview questions

hrithiksai67 said...

This Was An Amazing ! I Haven't Seen This Type of Blog Ever ! Thankyou For Sharing, data science course in hyderabad with placements

EXCELR said...


This post is really helpful for us. I certainly love this website, keep on it.
Data Science Course in Hyderabad

priyanka said...

Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple linear regression
data science interview questions

datasciencecourse said...

Cool stuff you have and you keep overhaul every one of us

Simple Linear Regression

Correlation vs Covariance

priyash said...

Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple linear regression
data science interview questions

piyasd said...

Amazing Article ! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple Linear Regression
data science interview questions
KNN Algorithm

Rohini said...

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
machine learning courses in bangalore

Priyanka said...

Attend The PMP Certification From ExcelR. Practical PMP Certification Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The PMP Certification.
PMP Certification

Kanika said...

Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
AWS Online Training
Online AWS Certification Training

priyanka said...

very well explained. I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Logistic Regression explained
Correlation vs Covariance
Simple Linear Regression
data science interview questions
KNN Algorithm

Tableau Training in Hyderabad said...



Nice article and thanks for sharing with us. Its very informative




Tableau Training in Hyderabad

Priyanka said...

Attend The Business Analytics Courses From ExcelR. Practical Business Analytics Courses Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Courses.
Business Analytics Courses

bbc bangla News said...

We are well established IT and outsourcing firm working in the market since 2013. We are providing training to the people ,
like- Web Design , Graphics Design , SEO, CPA Marketing & YouTube Marketing.Call us Now whatsapp: +(88) 01537587949
: Digital marketing training
Free bangla sex video:careful
good post Freelancing Training in bangladesh

Unknown said...

IEEE Final Year Project centers make amazing deep learning final year projects ideas for final year students Final Year Projects for CSE to training and develop their deep learning experience and talents.

IEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation.

corporate training in chennai corporate training in chennai

corporate training companies in india corporate training companies in india

corporate training companies in chennai corporate training companies in chennai

I have read your blog its very attractive and impressive. I like it your blog. Digital Marketing Company in Chennai Project Centers in Chennai

Mallela said...

Thanks for posting the best information and the blog is very helpful.digital marketing institute in hyderabad

Data Science Course in Varanasi - 360DigiTMG said...

Truly mind blowing blog went amazed with the subject they have developed the content. These kind of posts really helpful to gain the knowledge of unknown things which surely triggers to motivate and learn the new innovative contents. Hope you deliver the similar successive contents forthcoming as well.

data science in bangalore

Aishwariya said...

Awesome post.Really nice blog, i enjoyed your infomations. Thank you and i will expect more in future..keep it up!!
Amazon Web Services Training in Chennai

Mallela said...

Thanks for posting the best information and the blog is very important.digital marketing institute in hyderabad

Fyndhere said...

This is an informative post, looking for more. Please find local stores on fyndhere ios and andriod app

Rohini said...

Cool stuff you have and you keep overhaul every one of us, Great work.
pmp certification bangalore

salome said...

very interesting to read and detailed Angular training in Chennai

Post a Comment