做silvelight也有一段时间了,相册、游戏,刚刚完成的showcase这个小程序算是一个阶段了。这里就以showcase这个项目来做一下CaseStudy。
这一回我选择的数据方式是asp.net生成xml,用silverlight中的Linq来实例化成具体的类。
这里我以读取类别信息为例子,分为3步:
定义xml
<?xml version="1.0" encoding="utf-8" ?> <categories> <category><cid>2</cid><title>Dumex</title></category> <category><cid>1</cid><title>MySVW</title></category> <category><cid>3</cid><title>Microsoft</title></category> </categories>
定义实体类
public class Category { public int cid { get; set; } public string title { get; set; } }
用linq读取
WebClient client = new WebClient(); client.DownloadStringAsync(new Uri(HtmlPage.Document.DocumentUri, "category.ashx")); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { XmlReader reader = XmlReader.Create(new StringReader(e.Result)); XDocument document = XDocument.Load(reader); var categories = from c in document.Descendants("category") select new Category { cid = int.Parse(c.Element("cid").Value), title = c.Element("title").Value }; //todo }
在这里我选用了ashx来配合subsonic生成xml文件
<%@ WebHandler Language="C#" Class="category" %>
using System;
using System.Web;
using System.Text;
public class category : IHttpHandler {
StringBuilder sb = new StringBuilder();
string templateStr = "<category>" +
"<cid>{0}</cid>" +
"<title>{1}</title>" +
"</category>";
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/xml";
SC.CategoryCollection cc = new SC.CategoryCollection();
SubSonic.Query query = SC.Category.Query().ORDER_BY("sortid", "desc");
cc.LoadAndCloseReader(query.ExecuteReader());
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
sb.AppendLine("<categories>");
for (int i = 0; i < cc.Count; i++) {
sb.AppendLine(string.Format(templateStr, cc[i].Id, cc[i].Title));
}
sb.AppendLine("</categories>");
context.Response.Write(sb.ToString());
public bool IsReusable {
get {
return false;
}
作者:nasa
QQ:12446006