如何反序列化xml忽略节点类型的差异,即成员是表示为XmlElement还是表示为XmlAttribute。如何反序列化xml忽略节点类型中的差异(即是否XmlElement或XmlAttribute)
例如,我有这样的XML源
<Book>
<Title>Introduction to c#</Title>
<Publisher>John Smith</Publisher>
<Year>2012</Year>
<Book>
而且我想使用这个类
public class Book
{
public string Title{ get; set; }
[XmlAttribute()]
public string Publisher{ get; set; }
[XmlAttribute()]
public string Year{ get; set; }
}
反序列化它,你可以看到出版商和年份都标有“[XmlAttribute ]“在类中,所以它们不被反序列化。
有没有办法告诉反序列化器忽略成员表示为属性还是元素的差异?
我需要这在一个通用的转换器将一种类型转换到另一种相似类型
public static Type2 ConvertType1ToType2<Type1, Type2>(Type1 type1)
{
using (MemoryStream objectStream = new MemoryStream())
{
XmlSerializer type1Serializer = new XmlSerializer(typeof(Type1));
XmlSerializer type2Deserializer = new XmlSerializer(typeof(Type2));
type1Serializer.Serialize(objectStream, type1);
objectStream.Position = 0;
return (Type2)type2Deserializer.Deserialize(objectStream);
}
}
感谢您的回复。使用覆盖将要求我知道要覆盖的成员的名称。你知道有什么通用的方法来达到这个目的吗?我已经更新了这个问题以包含使用场景。 – adentum