I am trying to deserialize a custom class through an XmlSerializer and have several problems in that I don’t know the type that I am going to deserialize (it connects) and I am having difficulty defining it.
I found this post that looks similar, but cannot make it work with my approach, because I need to deserialize the interface, which is XmlSerializable.
What I have takes shape. Please note that I expect and should be able to handle both class A and class B, which will be implemented through the plugin. Therefore, if I can avoid using IXmlSerializable (which I think I cannot), that would be great.
ReadXml for A is what I'm stuck with. However, if there are other changes that I can make to improve the system, I will be happy to do so.
public class A : IXmlSerializable
{
public IB MyB { get; set;}
public void ReadXml(System.Xml.XmlReader reader)
{
SeekElement(reader, "MyB");
string typeName = reader.GetAttribute("Type");
Type bType = ???
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteStartElement("MyB");
writer.WriteAttributeString("Type", this.MyB.GetType().ToString());
this.MyB.WriteXml(writer);
writer.WriteEndElement();
}
private void SeekElement(XmlReader reader, string elementName)
{
ReaderToNextNode(reader);
while (reader.Name != elementName)
{
ReaderToNextNode(reader);
}
}
private void ReaderToNextNode(XmlReader reader)
{
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
{
reader.Read();
}
}
}
public interface IB : IXmlSerializable
{
}
public class B : IB
{
public void ReadXml(XmlReader reader)
{
this.X = Convert.ToDouble(reader.GetAttribute("x"));
this.Y = Convert.ToDouble(reader.GetAttribute("y"));
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("x", this.X.ToString());
writer.WriteAttributeString("y", this.Y.ToString());
}
}
NOTE. Updated as I realized that B had to use the IB interface. Sorry for the wrong question.
source
share