给定一个类型,我们不能直接控制在类级别的序列化:
public sealed class Class //contrived example{ public string Property {get;set;}}
而我们需要反序列化的xml:
<Class> <Property>Value</Property></Class>
您可以创建一个代理类型来手动处理目标类型的反序列化过程,如下所示:
[XmlRoot("Class")] // <-- Very importantpublic sealed class ClassSerializerProxy : IXmlSerializable{ public Class ClassValue {get;set;} public System.Xml.Schema.XmlSchema GetSchema(){return null;} public voID WriteXml(System.Xml.XmlWriter writer){} public voID readxml(System.Xml.XmlReader reader) { var x = XElement.ReadFrom(reader) as XElement; this.ClassValue = new Class(); //again this is a simple contrived example this.ClassValue.Property = x.XPathSelectElement("Property").Value; }}
用法是:
voID Main(){ // get the xml value somehow var xdoc= Xdocument.Parse(@"<Class><Property>Value</Property></Class>"); // deserialize the xml into the proxy type var proxy = Deserialize<ClassSerializerProxy>(xdoc); // read the resulting value var value = proxy.ClassValue;}public object Deserialize(Xdocument xmldocument,Type DeserializetoType){ XmlSerializer xmlSerializer = new XmlSerializer(DeserializetoType); using (XmlReader reader = xmldocument.CreateReader()) return xmlSerializer.Deserialize(reader);}
现在抛出一些泛型和扩展方法,我们可以清理一下最后一个(EXCEPT EXCEPTION HANDliNG)版本的调用站点:
用法:
voID Main(){ var xml = @"<Class><Property>Value</Property></Class>"; var value = xml.DeserializeWithProxy<ClassSerializerProxy,Class>(); value.Dump();}
您的实例类型:
public sealed class Class{ public string Property {get;set;}}
代理类型必须实现的接口
public interface ISerializerProxy<TInstanceType> where TInstanceType : class{ TInstanceType Value { get; }}
示例代理现在实现了新的接口
[XmlRoot("Class")]public sealed class ClassSerializerProxy : IXmlSerializable,ISerializerProxy<Class>{ public Class Value {get;set;} public System.Xml.Schema.XmlSchema GetSchema(){return null;} public voID WriteXml(System.Xml.XmlWriter writer){} public voID readxml(System.Xml.XmlReader reader) { var x = XElement.ReadFrom(reader) as XElement; this.Value = new Class(); this.Value.Property = x.XPathSelectElement("Property").Value; }}
反序列化方法现在是字符串的扩展方法,可以与任何代理类型一起使用.
public static class ExtensionMethods{ public static TInstanceType DeserializeWithProxy<TProxyType,TInstanceType>(this string xml) where TProxyType : ISerializerProxy<TInstanceType> where TInstanceType : class { using (XmlReader reader = Xdocument.Parse(xml).CreateReader()) { var xmlSerializer = new XmlSerializer(typeof(TProxyType)); return (xmlSerializer.Deserialize(reader) as ISerializerProxy<TInstanceType>).Value; } }}总结
以上是内存溢出为你收集整理的c# – 我可以提供XmlSerializer的自定义序列化,而不实现IXmlSerializable?全部内容,希望文章能够帮你解决c# – 我可以提供XmlSerializer的自定义序列化,而不实现IXmlSerializable?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)