Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gridview binding to 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:

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.

Code

<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>

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

like image 394
jpkeisala Avatar asked Dec 29 '22 06:12

jpkeisala


2 Answers

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

  1. Use Brian's solution, which is to rewrite the XML to use attributes instead of sub-nodes.
  2. Use an XSLT transform to dynamically convert the child nodes to attributes. See this SO question for an XSLT that can perform that operation.
  3. Load the XML data into a DataSet, which internally does this conversion.

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();

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.

like image 104
Eilon Avatar answered Jan 10 '23 08:01

Eilon


XmlDataSource works with attributes, not child entities. You need to do:

<node id="1096" name="About Us" ../>

Instead of using child elements. Unfortunately it is this way; I really wish it would work with the alternative; I like that approach much better.

like image 42
Brian Mains Avatar answered Jan 10 '23 08:01

Brian Mains