数据篇——从XML中获取数据
这个项目我的后台用的是asp.net开发。由于规模比较小我的数据层用的是subsonic。用它来做开发会比较敏捷。
这一回我选择的数据方式是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; } }
}
出处:蓝色理想
责任编辑:moby
上一页 全屏效果 下一页 加载图片
◎进入论坛RIA设计与应用版块参加讨论
|