Vladimir Nani

Vladimir Nani

  • NA
  • 108
  • 0

How use custom serialization?

Apr 1 2010 12:58 PM
Hello everybody i`m new to c#. Can you help me with understanding custom XML serialization.

Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Security.Permissions;


namespace ConsoleApplication3
{
public class ShoppingCartItem : ISerializable
{
public int productID;
public decimal price;
public int quantity;

[NonSerialized]
public decimal total;

public ShoppingCartItem():this(0,0,0){}
public ShoppingCartItem(int productID, decimal price, int quantity)
{
this.price = price;
this.productID = productID;
this.quantity = quantity;
total = price * quantity;
}
protected ShoppingCartItem(SerializationInfo info, StreamingContext sc)
{
this.price = info.GetDecimal("Price");
this.productID = info.GetInt32("Product ID");
this.quantity = info.GetInt32("Quantity");
}

//[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext sc)
{
info.AddValue("Price", price);
info.AddValue("Product ID", productID);
info.AddValue("Quantity", quantity);
}
[OnSerialized]
public void Calc(StreamingContext sc)
{
total = price * quantity;
}
[OnDeserialized]
public void Check(StreamingContext sc)
{
if ( total == 0 ) Calc(sc);
}
}

class Program
{
public static void Main()
{
ShoppingCartItem s = new ShoppingCartItem(5510, 1236, 12);
XmlSerializer xs = new XmlSerializer(typeof(ShoppingCartItem));
FileStream fs = new FileStream("new.xml", FileMode.Create);
xs.Serialize(fs, s);
fs.Close();
}
}
}


After serialization new.xml contains
<?xml version="1.0"?>
<ShoppingCartItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <productID>5510</productID>
  <price>1236</price>
  <quantity>12</quantity>
  <total>14832</total>
</ShoppingCartItem>

Why tags are not that which i had specified and why total is serialized?
Thanks.




Answers (2)