views:

313

answers:

3

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?

A: 

try changeing the xpath to

look like XPath="data/node"

Sean Barlow
Does not help. I have tried different paths and even different xml files.
jpkeisala
to use the data in your elements you need to you would need to do something like this to pull the id out of the xml. Brian makes a good point below that the XmlDataSouce uses attributes. <Columns> <asp:Label HeaderText="ID" SortExpression="id" Text="<%#XPath("ID")%>" /> </Columns>
Sean Barlow
+2  A: 

Hey,

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.

Brian
I don't understand what you've just said.
Jim Schubert
Ahh, it converted my example to HTML tags; sorry about that. It doesn't understand <node><id></id> syntax; it expects attributes as in <node id="1" name="test" desc="that" />.
Brian
+2  A: 

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.

Eilon