前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >XmlSerializerFactory Is Pretty Cool[转]

XmlSerializerFactory Is Pretty Cool[转]

作者头像
阿新
发布2018-04-12 18:52:08
6960
发布2018-04-12 18:52:08
举报
文章被收录于专栏:c#开发者

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.

代码语言:javascript
复制
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;

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2007-11-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档