using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
namespace SerializationExample
{
///
/// Shows XML serialization to the file with certain encoding set.
///
class Program
{
static void Main(string[] args)
{
XmlSerializer x = new XmlSerializer(typeof(SolarSystem));
SolarSystem o = new SolarSystem()
{
Name = "Slnečná sústava",
ObjectList = new List()
{
new Planet() { PlanetName = "Zem", Mass = 9999},
new Planet() { PlanetName = "Mars", Mass = 1234}
}
};
FileStream fileStream = new FileStream("file.txt", FileMode.CreateNew);
XmlWriter writer = new XmlTextWriter(fileStream, Encoding.UTF8);
x.Serialize(writer, o);
fileStream.Seek(0, SeekOrigin.Begin);
XmlReader reader = new XmlTextReader(new StreamReader(fileStream, Encoding.UTF8));
SolarSystem deserializedSolarSystem = (SolarSystem) x.Deserialize(reader);
Console.WriteLine(deserializedSolarSystem.Name);
fileStream.Close();
}
}
///
/// Serializable class. The [Serializable] attribut does not have to be there, if we
/// serialize using XmlSerializer, but if the class is intended for serialization, we should
/// put it there.
///
[Serializable]
public class SolarSystem
{
[XmlElement(ElementName = "Name")]
public string Name { get; set; }
///
/// This field will be ignored during the serialization.
///
[XmlIgnore]
public List ObjectList;
}
///
/// Inner serializable class.
///
[Serializable]
public class Planet
{
public string PlanetName { get; set; }
public double Mass { get; set; }
}
}