[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