Displaying XML Data in an ASP.NET page : Binding DataGrid to an XML File by Sriram Vaideeswaran.
Overview :
The .net framework provides the Dataset object which is designed to
handle data abstractly independent of the data source. The DataSet can handle
data from variety of sources like SQL, XML etc. In this article we'll show you
how to bind a data grid control to data in an XML file using the DataSet class.
In order access the DataSet class you must import the System.Data namespace
into your page.
<% @ Import NameSpace = "System.Data" %>
The DataSet has a ReadXML() method which is used to read data from an XML
file. For a DataSet to correctly read data from an XML file, the XML file should
be of the following format :
<RootElement>
<TableName>
<FieldName1>Field value</FieldName1>
<FieldName2>Field value</FieldName2>
<FieldName3>Field value</FieldName3>
<FieldName4>Field value</FieldName4>
</TableName>
<TableName>
<FieldName1>Field value</FieldName1>
<FieldName2>Field value</FieldName2>
<FieldName3>Field value</FieldName3>
<FieldName4>Field value</FieldName4>
</TableName>
......
</RootElement>
Where each TableName section represents a row of data from the
table.
Example :
<ProductList>
<Products>
<ProductId>1</ProductId>
<ProductName>Rice</ProductName>
<Rate>27</Rate>
</Products>
<Products>
<ProductId>2</ProductId>
<ProductName>Wheat</ProductName>
<Rate>20</Rate>
</Products>
</ProductList>
The name of the XML file along with the full path is passed as an argument to
the ReadXml method of the DataSet.
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Products1.xml"));
The DataSet can then be bound to the DataGrid using the DataBind() method of the
DataGrid.
DG1.DataSource = DS;
DG1.DataBind();
|