DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Migrate Serialized Java Objects with XStream and XMT
  • What Is Ant, Really?
  • Convert Payload From XML to Array of Objects by Comparing Mule 3 and Mule 4 Written Data Weave
  • Reading Attachments in Mule

Trending

  • Deploy a Session Recording Solution Using Ansible and Audit Your Bastion Host
  • How To Validate Archives and Identify Invalid Documents in Java
  • Agile Metrics and KPIs in Action
  • The Convergence of Testing and Observability
  1. DZone
  2. Coding
  3. Languages
  4. Serializing and deserializing objects to XML in C#

Serializing and deserializing objects to XML in C#

In this article, I will show some of the ways to serialize existing objects to XML and then deserialize them in C#.

Denzel D. user avatar by
Denzel D.
·
Jun. 15, 10 · Tutorial
Like (0)
Save
Tweet
Share
108.06K Views

Join the DZone community and get the full member experience.

Join For Free

Serialization is the process in converting specific information (data) to a format that can be stored or transmitted, and later re-used to retrieve the information in its initial state. In this article, I will show some of the ways to serialize existing objects to XML and then deserialize them.

First of all, I am going to have a custom class that represents a unit that contains data about a city:

public class City{    public string Name { get; set; }    public string State { get; set; }    public string County { get; set; }    public bool IsCountyCenter { get; set; }    public bool IsStateCapital { get; set; }    public int Population { get; set; }}

Before going any further, I need to instantiate the class and assign some values to the existing properties. Inside the main application class, I used the following code to customize my instance:

City city = new City();city.Name = "Independence";city.State = "KS";city.County = "Montgomery";city.IsCountyCenter = true;city.IsStateCapital = false;city.Population = 10000;

To serialize this specific object, I can use the XmlSerializer class. I’ve seen people who work with .NET write XML data via XmlWriter and retrieve each property, writing it to separate nodes. This is also a choice, however not the most reliable and since there is a built-in serialization class, unless it extremely doesn’t fit your needs, I’d recommend sticking with it.

The serialization code looks like this:

XmlSerializer serializer = new XmlSerializer(city.GetType());StreamWriter writer = new StreamWriter(@"D:\Temporary\myfile.xml");serializer.Serialize(writer.BaseStream, city);

The XmlSerializer instance accepts the object type as the parameter, so I am getting the type of the City instance. In my case, I am writing the serialization output to a file, however it can be written to any passed stream. The second parameter for the Serialize method is the instance that needs to be serialized.

The stored data will look like this:

<?xml version="1.0"?><City xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">  <Name>Independence</Name>  <State>KS</State>  <County>Montgomery</County>  <IsCountyCenter>true</IsCountyCenter>  <IsStateCapital>false</IsStateCapital>  <Population>10000</Population></City> 

The deserialization process goes the other way around – it converts the bytes of data obtained from a specific source to a workable object or data unit. In .NET, the same XmlSerializer class is used to deserialize data.

For the case presented above, the deserialization code looks like this:

City city = new City();XmlSerializer serializer = new XmlSerializer(city.GetType());StreamReader reader = new StreamReader(@"D:\Temporary\myfile.xml");object deserialized = serializer.Deserialize(reader.BaseStream);city = (City)deserialized;

First of all, I have an instance of the City class. It will become the deserialized object once the process is complete. Same as for the serialization process, I am getting the type for the target class instance and pass it to the existing XmlSerializer instance. The StreamReader will be the stream holder for the existing XML file. When initially deserialized, the data is represented by an object without a defined type. Later on, the developer can convert the object to fit the needed type and access the data.

Serialization not only saves a lot of time when existing data needs to be transferred or stored for later re-use, but it also makes the process more reliable by avoiding hand-written XML formatting and data placement mistakes.

XML Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Migrate Serialized Java Objects with XStream and XMT
  • What Is Ant, Really?
  • Convert Payload From XML to Array of Objects by Comparing Mule 3 and Mule 4 Written Data Weave
  • Reading Attachments in Mule

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: