How to

serialize/deserialize object to xml

Published: 26. September 2014 | Updated: 26. September 2014
License: Microsoft Public License (MS-PL)
Categories: Framework » XML
Tags: C# Serialization XML
Was this snippet helpful for you? YESYES / NONO
Get Analyzant!

Check your entire website from code to content in minutes with Analyzant, the free analysis suite.

Free download at analyzant.com

Import namespaces

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

Code

var path = Path.Combine(Environment.CurrentDirectory, "serialized.xml");
var obj = new MyClass { Id = 10, Text = "test" };

var serializer = new XmlSerializer(typeof(MyClass));

// serialize
using (var stream = File.Create(path))
{
    serializer.Serialize(stream, obj);
}

// deserialize
MyClass deserialized;
using (var stream = File.Open(path, FileMode.Open))
{
    deserialized = (MyClass)serializer.Deserialize(stream);
}

Class in example

[XmlRoot]
public class MyClass
{
    [XmlAttribute]
    public int Id { get; set; }

    [XmlElement]
    public string Text { get; set; }
}
Send us feedback about this snippet »



Related Snippets: