LinkedIn

Wednesday, 30 April 2008

Serialize a class into XML

To serialize a class into XML do the following:

FileStream fs = new FileStream("SerializedDate.XML", FileMode.Create);

// Create an XmlSerializer object to perform the serialization

XmlSerializer xs = new XmlSerializer(typeof(Acres.DataContracts.Data_NewCase_Contract));

// Use the XmlSerializer object to serialize the data to the file
Acres.DataContracts.Data_NewCase_Contract newCase = new Data_NewCase_Contract();
newCase.CaseId = 7;
newCase.CaseName = "caseSerialize";

xs.Serialize(fs, newCase);

// Close the file

fs.Close();

And the result is:
<?xml version="1.0"?>
<Data_NewCase_Contract xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CaseId>7</CaseId>
<CaseName>caseSerialize</CaseName>
</Data_NewCase_Contract>