0
0
CsharpHow-ToBeginner · 3 min read

How to Serialize to XML in C# - Simple Guide

To serialize an object to XML in C#, use the XmlSerializer class by creating an instance with the object's type and calling Serialize method with a stream or writer. This converts the object into XML format that can be saved or transferred.
📐

Syntax

The basic syntax to serialize an object to XML in C# involves creating an XmlSerializer for the object's type, then calling Serialize with a stream or writer to output the XML.

  • XmlSerializer serializer = new XmlSerializer(typeof(YourClass)); - prepares the serializer for your object type.
  • serializer.Serialize(stream, yourObject); - writes the XML representation of yourObject to the stream.
csharp
XmlSerializer serializer = new XmlSerializer(typeof(YourClass));
using (var stream = new FileStream("file.xml", FileMode.Create))
{
    serializer.Serialize(stream, yourObject);
}
💻

Example

This example shows how to serialize a simple Person object to an XML file named person.xml. It demonstrates creating the object, setting its properties, and saving it as XML.

csharp
using System;
using System.IO;
using System.Xml.Serialization;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        Person person = new Person { Name = "Alice", Age = 30 };
        XmlSerializer serializer = new XmlSerializer(typeof(Person));
        using (FileStream fs = new FileStream("person.xml", FileMode.Create))
        {
            serializer.Serialize(fs, person);
        }
        Console.WriteLine("XML serialization completed.");
    }
}
Output
XML serialization completed.
⚠️

Common Pitfalls

Common mistakes when serializing to XML include:

  • Trying to serialize types that are not public or do not have a parameterless constructor.
  • Not marking fields or properties you want to serialize as public.
  • Forgetting to close or dispose the stream or writer, which can cause incomplete files.
  • Serializing objects with circular references, which XmlSerializer does not support.

Always ensure your class is public and has a public parameterless constructor for serialization to work.

csharp
/* Wrong: private class or no parameterless constructor */
// This will cause an error
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(string name) { Name = name; }
}

/* Right: public class with parameterless constructor */
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person() { } // parameterless constructor
}
📊

Quick Reference

StepDescription
Create XmlSerializerXmlSerializer serializer = new XmlSerializer(typeof(YourClass));
Open Stream or WriterUse FileStream or StringWriter to write XML.
Call Serializeserializer.Serialize(stream, yourObject);
Close StreamDispose or close the stream to save the file properly.

Key Takeaways

Use XmlSerializer with the object's type to convert it to XML.
Ensure your class is public and has a parameterless constructor for serialization.
Always serialize to a stream or writer and properly close it to save XML.
Avoid serializing objects with circular references using XmlSerializer.
Use FileStream or StringWriter depending on whether you want a file or string output.