Search This Blog

Friday, June 12, 2009

How to bind an xml datasource to a gridview

XMl Document: books.xml
This is your xml document
-------------------------------
<?xml version="1.0" encoding="utf-8" ?>
<books>
   <book>
     <name> Ajax 2.0 </name>
     <specialization> Programming Language </specialization>
     <author>Wiley ,Bill</author>
     <publication>Wrox</publication>
     <price>200.00</price>
   </book>
   <book>
     <name> ASP.Net 3.5</name>
     <specialization>Web Programming Using C# and VB     </specialization>
     <author>Bill Thomas</author>
     <publication>Wrox</publication>
     <price>560.00</price>
   </book>
   <book>
     <name>C# 3.5 </name>
     <specialization> C# 2008 Powered by Microsoft     </specialization>
     <author> Microsoft Team </author>
     <publication>Wrox</publication>
     <price>600.00</price>
   </book>
</books>
-------------------------------
XSLT file: Books.xsl
This is your XSLT file code
-------------------------------
<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/">

      <books>
        <xsl:apply-templates select="//book"/>
      </books>

    </xsl:template>
    <xsl:template match="book">
      <xsl:if test="price > 200">
        <book>
         <xsl:attribute name="name">
          <xsl:value-of select="name"/>
         </xsl:attribute>
         <xsl:attribute name="specialization">
          <xsl:value-of select="specialization"/>
         </xsl:attribute>
         <xsl:attribute name="author">
          <xsl:value-of select="author"/>
         </xsl:attribute>
         <xsl:attribute name="publication">
           <xsl:value-of select="publication"/>
         </xsl:attribute>
         <xsl:attribute name="price">
          <xsl:value-of select="price"/>
         </xsl:attribute>
        </book>
      </xsl:if>
</xsl:template>
</xsl:stylesheet>

--------------------------
GridView Control
------------------------
add a gridview control in your web page with xmlDataSource as follows:
<asp:GridView ID="gvXML" runat="server" DataSourceID="XmlDataSource1">
<HeaderStyle BackColor="Gray" />
</asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/books.xml" TransformFile="~/BindGridView.xsl">
</asp:XmlDataSource>
Note:This control always look data in <book name="ask" price="1220"> </book>
format


After doing the above steps you will get the following output:










namespecializationauthorpublicationprice
ASP.Net 3.5Web Programming Using C# and VB Bill ThomasWrox560.00
C# 3.5 C# 2008 Powered by Microsoft Microsoft Team Wrox600.00

No comments:

Post a Comment