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
5510
1236
12
14832
Why tags are not that which i had specified and why total is serialized?
Thanks.
Jaish MathewsPosted Apr 1, 2010, 2:31 PM
I have straight answer for your "total" filed serialization issue. Because if u don't need to serialize a field, why need to mention it as public?. It's behaving like that i.e accessibility factor will override your serialization settings. If you don't need to serialise a filed, 1st behaviour expecting is that filed should be private. I made you field like below and now "total" not serializing.
[NonSerialized]private decimal total;
Vladimir NaniPosted Apr 1, 2010, 3:24 PM
Why when i say
info.AddValue("Price", price);
i have
but not