Looping through XML document

sujeesh picture sujeesh · Feb 11, 2013 · Viewed 35.3k times · Source

My XML file structure looks like this:

<SalaryDetails>
    <Employee>
        <Name>George Dsouza</Name>
        <AnnualSalary>320000</AnnualSalary>
        <DaysWorked>22</DaysWorked>
    </Employee>
    <Employee>
        <Name>Jackie Parera</Name>
        <AnnualSalary>300000</AnnualSalary>
        <DaysWorked>19</DaysWorked>
    </Employee>
...
</SalaryDetails>

I want to put all the data into database as employe records using XmlDocument.

So I wrote a loop like this:

XmlDocument xdcDocument = new XmlDocument();

xdcDocument.Load(@"D:\SalaryDetails.xml");

XmlElement xelRoot = xdcDocument.DocumentElement;
XmlNodeList xnlNodes = xelRoot.SelectNodes("/SalaryDetails/Employee");

foreach(XmlNode xndNode in xnlNodes)
    {
        //What to write here??
        //My sql insert command will go here
    }

AnnualSalary and DaysWorked are integers.

Answer

Shree picture Shree · Feb 11, 2013

try:

foreach (XmlNode xndNode in xnlNodes)
{
  string name= xndNode ["Name"].InnerText;
  string AnnualSalary= xndNode ["AnnualSalary"].InnerText;
  string DaysWorked= xndNode ["DaysWorked"].InnerText;

 //Your sql insert command will go here;
}