XML数据的分页显示
生活随笔
收集整理的這篇文章主要介紹了
XML数据的分页显示
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我的個人網站上有一個頁面,主要介紹了一些我喜歡的書籍,目前有9本,這樣把頁面拉的很長,挺影響美觀的,于是決定分頁顯示它們。我沒有SQL數據庫,而且我也不想用復雜的數據庫來存放這種簡單的數據,所以我用的是XML文件,把它讀入DataSet,然后再在Repeater中顯示。
如果是SQL數據庫或Access等,分頁到是挺簡單的,但是我存放數據的是XML文件,又不能用SQL語句,怎么辦呢?問了一個高手,知道了還有一種叫XPath的語言,又學到一些東西了,不敢偷懶,馬上記下。
//首先嘗試從緩存中讀取XmlDataDocument?doc?=?SiteCache.Get("Doc")?as?XmlDataDocument;
DataSet?ds?=?SiteCache.Get("Books")?as?DataSet;
if(doc?==?null?&&?ds?==?null)?{
????string?path;
????if(HttpContext.Current?!=?null)
????????path?=?HttpContext.Current.Server.MapPath("~/Content/Books.xml");
????else
????????path?=?Directory.GetCurrentDirectory()?+?Path.DirectorySeparatorChar?+?"Content/Books.xml";
????ds?=?new?DataSet();
????ds.ReadXml(path);
????
????doc?=?new?XmlDataDocument(ds);
????SiteCache.Max("Doc",?doc,?new?System.Web.Caching.CacheDependency(path));
????SiteCache.Max("Books",?ds,?new?System.Web.Caching.CacheDependency(path));
}
//總數據項為DataRow的個數
pager.TotalRecords?=?ds.Tables[0].Rows.Count;
int?current?=?pager.PageIndex?*?pager.PageSize;
int?target?=?current?+?pager.PageSize;
string?xpath?=?String.Format("/Books/Book[position()>{0}?and?position()<={1}]",?current,?target);
XmlNodeList?nodes?=?doc.DocumentElement.SelectNodes(xpath);
DataRow?row?=?null;
DataSet?ds2?=?ds.Clone();
ds2.Clear();
foreach(XmlNode?node?in?nodes)?{
????row?=?doc.GetRowFromElement((XmlElement)node);
????//ds2.Tables[0].Rows.Add(row);?不能用這樣的語句,否則會拋異常
????ds2.Tables[0].ImportRow(row);
}
books.DataSource?=?ds2;
books.DataBind();
上面的代碼中,pager是一個分頁控件,books是一個Repeater,用XPath選擇要讀取的節點,把它賦值到一個DataRow中,然后將之導入DataTable中,再綁定到Repeater上,就可以顯示了。這里遇到個小問題,不能用ds2.Tables[0].Rows.Add(row);這個語句,否則會拋個“此DataRow已屬于另一個DataTable”的異常,不知為什么,改為ImportRow就沒問題了。希望哪位高手知道,請告訴我一聲,謝謝。
http://chengbo.net/books.aspx
總結
以上是生活随笔為你收集整理的XML数据的分页显示的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在启用sharepoint portal
- 下一篇: RadioButton加入DataGri