<?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从入门到精通 | 张三 |