Archer
Archer

Reputation: 81

XmlDataSource in GridView

I have an xml file with the structure mentioned below:

<student>
  <name>Rahul</name>
  <name>Sheela</name>
</student>

I need to list the names of the students in a gridview.

Upvotes: 0

Views: 3202

Answers (3)

Mohamed abdelatty
Mohamed abdelatty

Reputation: 11

Create a XSLT transform file for your xml and add this fil to the data source (using "configre data source ") , this is used to re-shape your xml file so that the gridview can read it probably without the need of changing your xml structure , assuiming your xml structure is like this

  <student>
    <name>Rahul</name>
    <name>Sheela</name>
  </student>

your XSLT file should look like this

<xsl:stylesheet version="1.0" xmlns: xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com: xslt" exclude-result-prefixes="msxsl">
<xsl: output method="xml" indent="yes"/>
<xsl:template match ="/">
    <student>
      <xsl:apply-templates select ="//student"/>
    </student>
</xsl:template>
<xsl:template match ="//student">
    <student>
        <xsl:attribute name="name">
            <xsl:value-of select="name"/>
        </xsl:attribute>
    </student>
</xsl:template>
</xsl:stylesheet>

tell me if it work

Upvotes: 0

Simon Dugr&#233;
Simon Dugr&#233;

Reputation: 18916

You can use this synthax if it's possible for you to modify the way the XML file is rendered :

ASP.net markup page

<asp:GridView ID="GridView1" runat="server" DataSourceID="xmlDataSource" 
     AutoGenerateColumns="False">
    <RowStyle BackColor="#EFF3FB" />
    <Columns>
        <asp:TemplateField>
           <ItemTemplate>
              <%# Eval("name") %>
           </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:XmlDataSource ID="xmlDataSource" runat="server" DataFile="~/myxmlsource.xml" />

In this case, you have to modifiy your XML file if it's possible because I've allways work like that before, and after trying with your format, it is not working. Maybe a bit search on internet would say it is possible but haven't checked yet. Here is the format I've used and which is perfectly working:

XML file

<?xml version="1.0" encoding="utf-8" ?>
<students>
    <student name="Rahul" />
    <student name="Sheela" />
</students>

Upvotes: 0

Adil
Adil

Reputation: 148140

You can load that file in DataSet and bind that DataSet with the GridView.

DataSet ds = new DataSet();
ds.ReadXml("yourfile.xml")

gridview1.DataSource = ds;
gridview1.DataBind();

if your dataset has more then one tables and you may need to bind with table like this

gridview1.DataSource = ds.Tables[0]; // First table in the dataset.
gridview1.DataSource = ds.Tables[1]; // Second table in the dataset.

After change in Question

Two elements with same name under same parent, it would be Firstname, Lastname or RahulSheela

Upvotes: 1

Related Questions