C#自定义XML序列化 [英] C# Custom Xml Serialization
问题描述
我试图通过反序列化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.
使用ReadXML对于A是我卡在。但是,如果有其他的变化,我可以提高系统的话,我很乐意这样做。
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.
这篇关于C#自定义XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!