AdSense

Monday, 8 July 2013

C# - Serialize class in xml file

(Deutsche Version) To serialize classes into a file without having to care for the file structure, C# provides the so called serializer. This serializer can simply save complete classes (which can also contain sub classes). In a class, every object which shall be saved has to be marked:

[DataContract()]
public class TestClass
{
  [DataMember()]
  public int testInt = 5;
  [DataMember()]
  public string testString = "Test";
}


You have to put [DataContract()] in front of each class and [DataMember()] in front of every object. I also had to add a referency to System.Runtime.Serialization.

To serialize the class testClass wich is of the type TestClass, you only need 5 lines of code:

var writer = new FileStream("outputFileName.xml", FileMode.Create);
Type type = testClass.GetType();
DataContractSerializer serializer = new DataContractSerializer(type);
serializer.WriteObject(writer, testClass);
writer.Close();


The produced file looks like this:

<?xml version="1.0"?>
<TestClass xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/SerializeTest">
<test1>5</test1>
<test2>Test</test2>
</TestClass>


You can easily see which object has which value, which is not possible when serializing to files in binary format.


To read a serialized file, you have to execute these lines:

var reader = new FileStream("outputFileName.xml", FileMode.Open);
Type type = testClass.GetType();
DataContractSerializer deSerializer = new DataContractSerializer(type);
testClass = (TestClass)deSerializer.ReadObject(reader);
reader.Close();

No comments:

Post a Comment