Gridview 绑定到 XML [英] Gridview binding to XML

查看:27
本文介绍了Gridview 绑定到 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的网格视图,该视图绑定到一个简单的 xml 文档,但我必须遗漏一些东西,因为我不断收到错误消息:

I am trying to make a simple grid view that is binded to a simple xml document but I must be missing something since I am keep getting error message:

带有id的GridView的数据源'GridView1' 没有任何属性或属性生成列.确保您的数据源有内容.

The data source for GridView with id 'GridView1' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.

代码

<asp:GridView ID="GridView1" runat="server" DataSourceID="XmlDataSource1">
    <Columns>
        <asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" />
    </Columns>
</asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" 
    DataFile="Notifications.xml" XPath="/data/node"></asp:XmlDataSource>

XML

<?xml version="1.0" encoding="utf-8" ?>
<data>
  <node>
    <id>1096</id>
    <name>About Us</name>
    <date>21/12/2009 17:03:43</date>
    <user id="1">writer</user>
  </node>
  <node>
    <id>1099</id>
    <name>News</name>
    <date>21/12/2009 17:03:47</date>
    <user id="1">writer</user>
  </node>
  <node>
    <id>1098</id>
    <name>Another page</name>
    <date>21/12/2009 17:03:52</date>
    <user id="1">writer</user>
  </node>
</data>

可能是我的 xpath 出错了,还是我在这里做了一些根本性的错误?

Is it perhaps my xpath that is wrong or am I making something fundamentally wrong here?

推荐答案

有很多方法可以让这个工作:

There are a number of ways to get this to work:

  1. 使用 Brian 的解决方案,即重写 XML 以使用属性而不是子节点.
  2. 使用 XSLT 转换将子节点动态转换为属性.有关可以执行该操作的 XSLT,请参阅this SO question.
  3. 将 XML 数据加载到 DataSet 中,该数据集在内部执行此转换.

以下是如何执行 #3 的示例:

Here's an example of how to do #3:

DataSet ds = new DataSet();
ds.ReadXml(MapPath("~/App_Data/mydata.xml"));
GridView1.DataSource = ds;
GridView1.DataBind();

最后一种方法的局限性在于,您无法像使用数据源控件那样获得自动数据绑定.但是,由于 XmlDataSource 无论如何都是只读控件,因此这不一定是一个严重的限制.

The limitation of this last approach is that you don't get automatic databinding as you would with a data source control. However, since the XmlDataSource is a read-only control anyway, that's not necessarily a serious limitation.

这篇关于Gridview 绑定到 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆