在 WCF 服务中,现在无法迁移到DataContract Serialization
。我需要控制 xml 序列化默认行为。
这是我的 POCO 课程,我需要在这些课程上完全控制序列化过程。
[Serializable]
public class ProductBase
{
public int Id { get; set; }
}
[Serializable]
public class DurableProduct : ProductBase
{
public string Name { get; set; }
public Price Pricing { get; set; }
}
[Serializable]
public class Price : IXmlSerializable
{
public int Monthly { get; set; }
public int Annual { get; set; }
}
我需要控制类的序列化过程DurableProduct
,Price
. 因此,我IXmlSerializable
在这些类上实现了如下 -
[Serializable]
public class DurableProduct : ProductBase, IXmlSerializable
{
public string Name { get; set; }
public Price Pricing { get; set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
Id = int.Parse(reader.ReadElementString());
Name = reader.ReadElementString();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("Id", Id.ToString());
writer.WriteElementString("Name", Name);
}
public override string ToString()
{
return string.Format("Id : {0}, Name: {1}, Monthly: {2}", Id, Name, Pricing.Monthly);
}
}
[Serializable]
public class Price : IXmlSerializable
{
public int Monthly { get; set; }
public int Annual { get; set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
//Control never reaches here, while deserializing DurableProduct
Monthly = int.Parse(reader.ReadElementString());
Annual = int.Parse(reader.ReadElementString());
}
public void WriteXml(XmlWriter writer)
{
//Control never reaches here, while deserializing DurableProduct
writer.WriteElementString("MyCustomElement1", Monthly.ToString());
writer.WriteElementString("MyCustomElement2", Annual.ToString());
}
}
问题当我尝试序列化/反序列化时IXmlSerializable => ReadXml / WriteXml
,没有调用类。
如何实现我的类,以便可靠地调用 IXmlSerializable 的所有读/写实现。