今天沒有什麼事,在網上看到用LINQ to XML來操作Sitemap,自己感覺很有用,所有就寫出來與大家一起分享,雖然很簡單,但是我還是要寫,可能對以後大家做項目有一點協助;如是你是牛X的人,你可以不看,如果你是初學者,推薦你可以看看;
1.首先我們要建立一個Web.Sitemap XML檔案;代碼如下所示:
<?xml version="1.0" encoding="utf-8"?><siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"> <siteMapNode title="My Favorites"> <siteMapNode title="Favorite Sites"> <siteMapNode title="ASP.NET Home" url="http://www.asp.net" /> <siteMapNode title="ASP.NET Articles" url="http://www.dotnetcurry.com"/> <siteMapNode title="Windows Client" url="http://www.windowsclient.net" /> <siteMapNode title="Silverlight" url="http://silverlight.net" /> </siteMapNode> <siteMapNode title="Favorite Blogs"> <siteMapNode title="ScottGu Blog" url="http://weblogs.asp.net/scottgu"/> <siteMapNode title="Technology Blog" url="http://www.devcurry.com" /> <siteMapNode title="SQL Blog" url="http://www.sqlservercurry.com" /> <siteMapNode title="Food Lovers" url="http://foodatarian.com" /> </siteMapNode> <siteMapNode title="Favorite Social Sites"> <siteMapNode title="Twitter" url="http://twitter.com/"/> <siteMapNode title="FaceBook" url="http://www.facebook.com" /> <siteMapNode title="LinkedIn" url="http://www.linkedin.com" /> <siteMapNode title="Orkut" url="http://www.orkut.com" /> </siteMapNode> </siteMapNode></siteMap>
2.第二步,我們為分頁檔中添加一個控制項,在這裡我用的是bulletedList,並把它的顯示方式設為Hyperlink,代碼如下:
<head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <asp:BulletedList ID="linkList" DisplayMode="HyperLink" runat="server"> </asp:BulletedList> </div> </form></body></html>
3.用LINQ to XML來讀出XML檔案中的所有的URL,代碼如下所示:
#region 用LINQ顯示出所有的URL public void ShowURL() { XElement xelement = XElement.Load(Server.MapPath("Web.sitemap")); var urllist = xelement.Descendants().Attributes().Where(x => x.Name == "url")
.Select(x => x.Value); foreach (string item in urllist) { this.linkList.Items.Add(item); } } #endregion
運行效果出下:
4.用Linq to Xml 來讀取Url和title 並顯示,代碼如下所示
#region 用LINQ顯示URL和Title public void ShowUrlandTitle() { XElement xelement = XElement.Load(Server.MapPath("Web.sitemap")); var urlandTitle = xelement.Descendants().Where(element =>
element.LastAttribute.Name.LocalName.Contains("url")) .Select(nd => new { title = nd.Attribute("title").Value, url = nd.Attribute("url").Value }); foreach (var item in urlandTitle) { ListItem i = new ListItem(item.title, item.url); this.linkList.Items.Add(i); } } #endregion
運行效果如下所示:
5.用Linq to xml讀出指定的資料,代碼如下所示:
#region 顯示指定的資料資訊 public void ShowPart() { XElement xelement = XElement.Load(Server.MapPath("Web.sitemap")); var node = xelement.Descendants().Where(sel =>
(string)sel.Attribute("title") == "Favorite Social Sites") .SelectMany(sel => sel.Elements()).Select(nd =>
new { title = nd.Attribute("title").Value, url = nd.Attribute("url").Value }); foreach (var item in node) { ListItem i = new ListItem(item.title, item.url); this.linkList.Items.Add(i); } } #endregion
運行效果如下:
關於linq to xml的操作有很多相關的文章,我在這裡也是最基本的操作,如果你是初學者想到更高的層次,建議可以到MSDN上去學習;