Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

c# - Why does the OnDeserialization not fire for XML Deserialization?

I have a problem which I have been bashing my head against for the better part of three hours. I am almost certain that I've missed something blindingly obvious...

I have a simple XML file:

<?xml version="1.0" encoding="utf-8"?>
<WeightStore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:xsd="http://www.w3.org/2001/XMLSchema">  
  <Records>
    <Record actual="150" date="2010-05-01T00:00:00" />
    <Record actual="155" date="2010-05-02T00:00:00" />
  </Records>
</WeightStore>

I have a simple class structure:

[Serializable]
public class Record
{
    [XmlAttribute("actual")] public double weight { get; set; }
    [XmlAttribute("date")]   public DateTime date { get; set; }
    [XmlIgnore]              public double trend { get; set; }
}

[Serializable]
[XmlRoot("WeightStore")]
public class SimpleWeightStore
{
    [XmlArrayAttribute("Records")]
    private List<Record> records = new List<Record>();
    public List<Record> Records { get { return records; } }

    [OnDeserialized()]
    public void OnDeserialized_Method(StreamingContext context)
    {
        // This code never gets called
        Console.WriteLine("OnDeserialized");
    }
}

I am using these in both calling code and in the class files:

using System.Xml.Serialization;
using System.Runtime.Serialization;

I have some calling code:

SimpleWeightStore weight_store_reload = new SimpleWeightStore();
TextReader reader = new StringReader(xml);
XmlSerializer deserializer = new XmlSerializer(weight_store.GetType());
weight_store_reload = (SimpleWeightStore)deserializer.Deserialize(reader);

The problem is that I am expecting OnDeserialized_Method to get called, and it isn't.

I suspect it might have something to do with the fact that it's XML deserialization rather than Runtime deserialization, and perhaps I am using the wrong attribute name, but I can't find out what it might be.

Any ideas, folks?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's no equivalent of OnDeserialized for XML deserialization.

See this post for workarounds: How do you find out when you've been loaded via XML Serialization?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...