- Open the WCF service application that you created earlier.
- Add a new project using Windows > Console application template
- Lets name it SerializationDemo
- Add reference to the WCF Service project and also add reference to System.Runtime.Serialization and System.IO
- Add the following code
{
ProductReview p = new ProductReview() { Id = "001", ProductCode = "12", ProductName = "Mask", Review = "Very Good!" };
DataContractSerializer dcs = new DataContractSerializer(typeof(ProductReview));
//Serialize
using (FileStream fs = new FileStream("ProductReview.xml", FileMode.Create))
{
dcs.WriteObject(fs, p);
}
//Deserialize
using (FileStream fs = new FileStream("ProductReview.xml", FileMode.Open))
{
ProductReview pr = (ProductReview)dcs.ReadObject(fs);
Console.WriteLine("Product Name: {0} \nCustomer Review: {1}", pr.ProductName, pr.Review);
}
Console.ReadKey();
}
Testing the project
- Run the project.
- Go to the bin/Debug folder of the project.
- Examine the ProductReview.xml file in the Internet Explorer
- Notice how ProductReview instance has be serialized into XML.
- Note the following:
- The outer most element is same as the name of the class annotated with [DataContract] attribute
- There is an inner element for each property annotated with [DataMember] attribute.
- Inner elements are in the alphabetical order.
Customizing the mapping to XML element
You can customize how the class annotated with DataContract and DataMember maps to XML elements. You can do this by setting the properties of DataContractAttribute class and DataMemberAttribute class.
Comments
Post a Comment