<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="張三" ISBN="2-3631-4">
<title>CS從入門到精通</title>
<author>候捷</author>
<price>59</price>
</book>
</bookstore>
現在要把這兩條記錄顯示在GridView裏,數據源用XmlDataSource 讀取上面的XML:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="XmlDataSource1" Width="200px">
<Columns>
<asp:TemplateField HeaderText="名稱">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# XPath("title") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="genre">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("genre") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/XML/Bookstore.xml" XPath="bookstore/book">
</asp:XmlDataSource>
看見了嗎,以上兩列的綁定是不同的,其中“名稱”列爲book節點的子節點,不是其屬性,因此要用XPath 進行尋找並綁定(如果這裏用Bind就錯了),同理genre爲book節點的屬性,只需要用Bind綁定即可。另外要注意XPath的設置,它實際就是從根節點到你要顯示的數據的節點的路徑。
以上現實結果爲:
名稱 | genre |
---|---|
Oberon's Legacy | fantasy |
CSS從入門到精通 | 張三 |