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.
- 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
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.
220 comments:
«Oldest ‹Older 201 – 220 of 220 Newer› Newest»
-
Anonymous
said...
-
-
March 20, 2024 at 1:55 PM
-
Anonymous
said...
-
-
April 6, 2024 at 12:16 PM
-
Anonymous
said...
-
-
April 29, 2024 at 3:11 AM
-
Swetha
said...
-
-
May 25, 2024 at 7:59 AM
-
Anonymous
said...
-
-
June 13, 2024 at 7:37 PM
-
Anonymous
said...
-
-
June 15, 2024 at 12:22 PM
-
Anonymous
said...
-
-
October 31, 2024 at 8:46 AM
-
Anonymous
said...
-
-
June 3, 2025 at 10:05 AM
-
ONLINE IT GURU
said...
-
-
February 26, 2026 at 10:58 AM
-
Suvarna
said...
-
-
April 3, 2026 at 1:49 PM
-
Suvarna
said...
-
-
April 3, 2026 at 1:51 PM
-
Suvarna
said...
-
-
April 3, 2026 at 1:58 PM
-
Digital Solution
said...
-
-
April 13, 2026 at 9:16 AM
-
Digital Solution
said...
-
-
April 13, 2026 at 1:12 PM
-
Digital Solution
said...
-
-
April 20, 2026 at 12:32 PM
-
Anonymous
said...
-
-
April 22, 2026 at 1:52 PM
-
Nikah Namah
said...
-
-
April 30, 2026 at 3:11 PM
-
The Millenials
said...
-
-
May 3, 2026 at 1:31 PM
-
Parlay Hair And Beauty Salon
said...
-
-
May 5, 2026 at 9:32 AM
-
Digital Solution
said...
-
-
May 14, 2026 at 11:42 AM
«Oldest ‹Older 201 – 220 of 220 Newer› Newest»Привет, я Александр! Хочу поделиться своим восторженным отзывом о казино Вавада. Благодаря вавада зеркало рабочее на сегодня мобильная vavadacag1, я обнаружил потрясающий мир азарта онлайн. Уже с первых минут игры меня покорили великолепные слоты и щедрые бонусы. Не могу не отметить простую и быструю регистрацию, что очень удобно. Каждый раз, когда играю в Вавада, приятно осознавать, что мои выигрыши будут выплачены оперативно. Интерфейс казино простой в использовании, что другое говорит за его удобство. Помимо этого, приветственный бонус и фриспины позволяют мне начать игру с крупной суммой. Всем любителям азарта настоятельно рекомендую посетить вавада зеркало рабочее на сегодня мобильная vavadacag1 и насладиться незабываемым опытом игры в казино Вавада.
Друганы, я нашел классные картинки и фото по теме Тоби Акацуки арт! Вы не поверите, какой стиль и красота в этих работах. Обязательно зайдите на эту ссылочку тоби акацуки арт, чтобы посмотреть все это великолепие своими глазами. Там целых 33 фото, каждая уникальная и впечатляющая. Уверяю, вам точно понравится, так что не упустите возможность насладиться этими прекрасными художественными работами!
Привет! Если ищешь классную открытку на 6 месяцев для маленького мальчика, то точно попал по адресу! Можете бесплатно скачать открыточку по ссылке: Открытка на 6 месяцев ребенку мальчику скачать. Там шикарный дизайн, с няшными рисунками, которые качество просто прёт, а текст на открытке просто милота! Обязательно скачай и порадуй малыша!
Thank you for your positive feedback! I'm glad you found the article informative and that it effectively communicates the entire concept in detail. Your appreciation is greatly appreciated!click here for more information
Привет! Если ты, как и я, обожаешь всякие красивые картинки и фото, то обязательно загляни на эту ссылку! Там настоящая бомба вас ждет - вертикальный фон! У них там огромный выбор разных фотографий с вертикальной композицией. Вот только представь, сколько крутых обоев можно найти на свой компьютер или телефон! Так что не затягивай, бегом тыкать на ссылку и наслаждаться прекрасными фонами!
Если у тебя скоро братишка имеет день рождения, то я знаю, что он будет очень доволен, если ты сделаешь ему приятный сюрприз - открытку! Просто отпечатай на глянцевой бумаге открытку с днем рождения для брата от сестры, и уверен, что он засмеется и будет рад. Это просто зачетное решение, которое можно всегда взять и скачать бесплатно открытку с днем рождения брату от сестры на PoZdravlenya.ru. Там ты найдешь много вариантов для любого стиля, ну и необычные поздравления. Так что не жди, иди на сайт и поздравляй своего брата с Днем Рождения стильно и оригинально!
شركة تسليك مجاري 4kwAtAS4LF
شركة تسليك مجاري بالخبر
GcFmRwyKtU
Enhance your career with comprehensive salesforce development training
designed to teach you the skills needed to build, customize, and deploy Salesforce applications.
Great explanation! Your article clearly highlights the importance of cybersecurity skills in today’s digital age. I agree that learning through practical exposure and expert mentorship is essential. Platforms like Digital Marketing Training in Hyderabad offer real-time projects and placement support, which helps learners build confidence and industry readiness.
Amazing insights shared here! I appreciate how you made cybersecurity concepts easy to understand. It’s true that real-world experience is crucial for mastering these skills. Institutes offering Digital Marketing Course in Hyderabad focus on practical training and expert mentorship, which is very beneficial for learners.
Very informative post! Your explanation of cybersecurity threats and solutions was very clear. I believe practical training and real-time projects are essential for skill development. Platforms like Digital Marketing Training in Hyderabad provide this kind of learning environment along with placement support, which is highly valuable.
This is where a specialized Architectural Design Course in Pune
becomes a career-defining investment. Whether you are struggling to convert academic knowledge into practical output or are a professional aiming to add photorealistic rendering to your portfolio, the right training institute bridges the gap between theoretical design and real-world project execution.
Looking for a reliable Wine Store near by myrtle beach hotels
? Beach Discount Beverages is your go-to spot for premium wines, spirits, and refreshing drinks just minutes from your stay. Whether you're planning a beach party or a quiet evening, explore a wide selection at affordable prices. Enjoy friendly service, quick shopping, and great value every time you visit. Don’t miss out—stop by today and grab your favorites with ease. Visit us at 2204 North Kings Highway, Myrtle Beach, SC 29577 or call (843) 916-9542 to check availability and current deals.
Start your journey into python programming with Envision Computer Training Institute. Learn by doing real projects, guided by experienced trainers who focus on clarity and hands-on skills. Build confidence as you write code, solve problems, and understand core concepts. Take action today and explore a learning environment designed to help beginners and professionals grow step by step in a supportive and practical way.
تنظيف فلل وشقق بالقطيف
Explore safe Muslim marriage profiles designed for people seeking halal and meaningful connections. Nikah Namah creates a secure space where families and individuals can search for trusted matches with confidence and comfort.
Finding the right partner can feel overwhelming. Look for honesty, experience, and clear communication. The Millenials stand out by offering practical solutions and real support. If you’re asking how to find a trustworthy CBD marketing partner, choose a team that explains the process, sets realistic goals, and works alongside you every step of the way.
Stuart friends, we’re just a short drive away. Come visit your hair salon near stuart florida – Parlay Hair And Beauty Salon welcomes you with coffee, conversation, and skilled hands. Whether you need a polish or a full change, we’ve got you. Take the ride, feel the difference.
What makes a great performance marketing agency? Results you can touch. Search Extension transforms strategies into sales, gently guiding customers to your door. No empty promises, just dedicated support. Curious how? Search Extension – discover our story and start your success. We’re here to make marketing feel good again.
Post a Comment