Gridview 绑定到 XML

编程入门 行业动态 更新时间:2024-10-28 00:15:19
本文介绍了Gridview 绑定到 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试制作一个简单的网格视图,该视图绑定到一个简单的 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:

使用 Brian 的解决方案,即重写 XML 以使用属性而不是子节点.使用 XSLT 转换将子节点动态转换为属性.有关可以执行该操作的 XSLT,请参阅this SO question.将 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 10:50:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/828178.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   Gridview   XML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!