ASP.NET 2.0提供了多種數據源,一般情況下,XmlDataSource控件使用XML文件,下面的例子就是使用XmlDocument對象進行數據綁定的一種方法。
VB.NET代碼
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim doc As New System.Xml.XmlDocument
doc.Load("http://dotnet.aspx.cc/Rss.aspx")
XmlDataSource1.Data = doc.InnerXml
XmlDataSource1.XPath = "/rss/channel/item"
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" DataSourceID="XmlDataSource1" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="文章標題">
<ItemTemplate>
<asp:HyperLink runat="server" Target="_blank" NavigateUrl='<%#XPath("link") %>'>
<%#XPath("title")%></asp:HyperLink>
[<%#CType(XPath("pubDate"), DateTime).ToString("yyyy年M月d日")%>]
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server"></asp:XmlDataSource>
</form>
</body>
</html>
C#代碼
<%@ Page Language="C#" AutoEventWireup="true"%>
<script runat="server">
protected void Page_Load( object sender, System.EventArgs e )
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load("http://dotnet.aspx.cc/Rss.aspx");
XmlDataSource1.Data = doc.InnerXml;
XmlDataSource1.XPath = "/rss/channel/item";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" DataSourceID="XmlDataSource1" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="文章標題">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Target="_blank" NavigateUrl='<%#XPath("link") %>'>
<%#XPath("title")%></asp:HyperLink>
[<%#(DateTime.Parse(XPath("pubDate").ToString().Replace("GMT",""))).ToString("yyyy年M月d日")%>]
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server"></asp:XmlDataSource>
</form>
</body>
</html>