未知类型的自定义Xml序列化 [英] Custom Xml Serialization of Unknown Type
问题描述
我正在尝试通过XmlSerializer反序列化自定义类,并遇到一些问题,因为我不知道要反序列化的类型(可插入),并且遇到了困难确定它.
I'm attempting to deserialize a custom class via the XmlSerializer and having a few problems, in the fact that I don't know the type that I'm going to be deserializing (it's pluggable) and I'm having difficulty determining it.
我发现了这篇文章,它看起来很相似,但是不能非常适合我的方法,因为我需要反序列化XmlSerializable接口.
I found this post which looks similar but can't quite get it to work with my approach because I need to deserialize an interface which is XmlSerializable.
我现在得到的是表格.请注意,我期望并且需要能够处理通过插件实现的A类和B类.因此,如果我可以避免使用IXmlSerializable(我认为我不能这样做),那就太好了.
What I've currently got is of the form. Note that I expect and need to be able to handle both class A and class B to be implemented via a plugin. So if I can avoid using the IXmlSerializable (which I don't think I can) then that would be great.
A的ReadXml是我所坚持的.但是,如果我还有其他可以改进系统的更改,那么我很乐意这样做.
The ReadXml for A is what I'm stuck on. However if there are other changes that I can make to improve the system then I'm happy to do so.
public class A : IXmlSerializable
{
public IB MyB { get; set;}
public void ReadXml(System.Xml.XmlReader reader)
{
// deserialize other member attributes
SeekElement(reader, "MyB");
string typeName = reader.GetAttribute("Type");
// Somehow need to the type based on the typename. From potentially
//an external assembly. Is it possible to use the extra types passed
//into an XMlSerializer Constructor???
Type bType = ???
// Somehow then need to deserialize B's Members
// Deserialize X
// Deserialize Y
}
public void WriteXml(System.Xml.XmlWriter writer)
{
// serialize other members as attributes
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());
}
}
注意:已更新,因为我意识到B应该使用接口IB.抱歉,您提出的问题有误.
NOTE : Updated as I realised B was supposed to use interface IB. Sorry for slightly wrong question.
推荐答案
要从字符串创建实例,请使用Activator.CreateInstance的重载之一.要仅获取具有该名称的类型,请使用Type.GetType.
To create an instance from a string, use one of the overloads of Activator.CreateInstance. To just get a type with that name, use Type.GetType.
这篇关于未知类型的自定义Xml序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!