數(shù)據(jù)篇——從XML中獲取數(shù)據(jù)
這個(gè)項(xiàng)目我的后臺(tái)用的是asp.net開發(fā)。由于規(guī)模比較小我的數(shù)據(jù)層用的是subsonic。用它來做開發(fā)會(huì)比較敏捷。
這一回我選擇的數(shù)據(jù)方式是asp.net生成xml,用silverlight中的Linq來實(shí)例化成具體的類。
這里我以讀取類別信息為例子,分為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>
- 定義實(shí)體類
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; } }
}
出處:藍(lán)色理想
責(zé)任編輯:moby
上一頁 全屏效果 下一頁 加載圖片
◎進(jìn)入論壇RIA設(shè)計(jì)與應(yīng)用版塊參加討論
|