Reading XML using DataSet Class
In this article we will discuss
how to read and XML File using object of DataSet Class.
Sample XML File
Employee.xml
<?xml version="1.0" ?>
<EMPLOYEES>
<EMP>
<EMPNO>7369</EMPNO>
<ENAME>SMITH</ENAME>
<JOB>CLERK</JOB>
<MGR>7902</MGR>
<HIREDATE>17-DEC-80</HIREDATE>
<SAL>800</SAL>
</EMP>
<EMP>
<EMPNO>7499</EMPNO>
<ENAME>ALLEN</ENAME>
<JOB>SALESMAN</JOB>
<MGR>7698</MGR>
<HIREDATE>20-FEB-81</HIREDATE>
<SAL>1600</SAL>
<COMM>300</COMM>
</EMP>
<EMP>
<EMPNO>7521</EMPNO>
<ENAME>WARD</ENAME>
<JOB>SALESMAN</JOB>
<MGR>7698</MGR>
<HIREDATE>22-FEB-81</HIREDATE>
<SAL>1250</SAL>
<COMM>500</COMM>
</EMP>
<EMP>
<EMPNO>7566</EMPNO>
<ENAME>JONES</ENAME>
<JOB>MANAGER</JOB>
<MGR>7839</MGR>
<HIREDATE>02-APR-81</HIREDATE>
<SAL>2975</SAL>
</EMP>
<EMP>
<EMPNO>7654</EMPNO>
<ENAME>MARTIN</ENAME>
<JOB>SALESMAN</JOB>
<MGR>7698</MGR>
<HIREDATE>28-SEP-81</HIREDATE>
<SAL>1250</SAL>
<COMM>1400</COMM>
</EMP>
</EMPLOYEES>
Snippet to read the XML File
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Reading_XML_Data
{
public
partial class Form1 : Form
{
public
Form1()
{
InitializeComponent();
}
private
void Form1_Load(object
sender, EventArgs e)
{
DataSet
ds = new DataSet();
ds.ReadXml(@"D:\Employee.xml");
foreach
(DataRow dr in
ds.Tables["EMP"].Rows)
{
MessageBox.Show("Employee
ID: " + dr["EMPNO"] +
" Name: " + dr["ENAME"]);
}
}
}
}
Here,
DataSet ds = new DataSet();
We create an instance of
DataSet Class
ds.ReadXml(@"D:\Employee.xml");
The ReadXml method of
DataSet class is used to read XML data from the File Specified here
(Employee.xml) and Load it to the DataSet.
The parameter to the
ReadXml method is the Location of Employee.xml File
foreach (DataRow dr
in ds.Tables["EMP"].Rows)
{
MessageBox.Show("Employee
ID: " + dr["EMPNO"] +
" Name: " + dr["ENAME"]);
}
Here we read the rows from the
dataset using DataRow class and looping through the rows in the DataSet ds.
Hope this might help you a
little.
Thanks for reading