XmlSerializerFactory Is Pretty Cool[转]
The XmlSerializerFactory is a new class in .NET 2.0 that provides a factory pattern over the XmlSerializer. It maintains the cache of generated assemblies so that you can avoid the XmlSerializer leaks. Usage doesn't impact your code much at all.
Here is a quick demo that I threw together. I pulled up my blog's RSS feed and saved it into my Visual Studio project as "XmlFile1.xml". I then created a schema from it (in Visual Studio, use the "XML/Create Schema" menu item). Using the schema, I created a serializable class from that schema. This is simple using the command line tools:
xsd.exe /classes xmlfile1.xsd xmlfile11.xsd xmlfile12.xsd xmlfile13.xsd
The result was a set of XML serializable classes that are already decorated with the appropriate attributes for serialization. The last step is to use the serializable classes with the XmlSerializer.
public rss GetFeed(Uri location)
{
XmlSerializerFactory factory = new XmlSerializerFactory();
XmlSerializer ser = factory.CreateSerializer(typeof(rss));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(location);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
rss feed = (rss)ser.Deserialize(responseStream);
responseStream.Close();
return feed;
}
A bonus is that in .NET 2.0, the generated types will have public properties by default, which enables rapid UI development using data binding. I created a Windows Form with a grid and used the new databinding features to bind to the generated XML serializable classes, using the ObjectDataSource control. The result is that my UI code is drastically reduced to create a simple grid UI that displays the data:
rss feed = GetFeed(new Uri("http://blogs.msdn.com/kaevans/rss.aspx"));
this.dataGridView1.DataSource = feed.channel.item;
this.Text = feed.channel.title + " - " + feed.channel.description;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix