Sign in to follow this  
Daniel Protopopov

C# Serialization

Recommended Posts

Hi there, I'm having problems de-serializing class from XML file which has the following structure:
public class IState : IXmlSerializable
{
...

public virtual void WriteXml(XmlWriter XMLWriter)
        {
            
        }

        public virtual void ReadXml(XmlReader XMLReader)
        {
            if (!XMLReader.HasAttributes)
                return;
        }

        public virtual XmlSchema GetSchema()
        {
            return null;
        }
}
public class CustomState : IState, IXmlSerializable
{
// ...

public override void WriteXml(XmlWriter XMLWriter)
        {
            base.WriteXml(XMLWriter);

            // ...
        }

        public override void ReadXml(XmlReader XMLReader)
        {
            base.ReadXml(XMLReader);

            if (!XMLReader.HasAttributes)
                return;

            // ...
     }
}
When serializing CustomState into XML file, I get this:
<?xml version="1.0" encoding="utf-8"?><CustomState Position="26400,24900" Radius="1100" />
However when I try to de-serialize it back using IState as a base like this:
System.Xml.XmlReader Reader = new System.Xml.XmlTextReader(Dialog.FileName);
                XmlDocument XMLDocument = new XmlDocument();
                XMLDocument.Load(Reader);

                Type ObjectType = Type.GetType(XMLDocument.FirstChild.NextSibling.Name);
                XmlSerializer XMLReader = new XmlSerializer(ObjectType);
                IState NewState = null;
                try
                {
                    NewState = (IState)XMLReader.Deserialize(Reader);
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    if (NewState != null)
                        Context.State = NewState;

                    Reader.Close();
                }
I am receiving 'null' and it fails to de-serialize CustomState from the XML file. Can any of you tell me the proper way to de-serialize class that derives from (abstract) other class? This is how I serialize all IState-derived classes:
XmlSerializer XMLWriter = new XmlSerializer(Context.State.GetType());
                System.IO.TextWriter TextWriter = new System.IO.StreamWriter("DefaultState.xml");
                System.Xml.XmlWriter Writer = new System.Xml.XmlTextWriter(TextWriter);
                XMLWriter.Serialize(Writer, Context.State);

                Writer.Close();
                TextWriter.Close();
Many thanks, Daniel

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this