Looping through XML document

35,654

Solution 1

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;
}

Solution 2

You can also use XDoc and XElement to get the element values using the LINQ way. http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx

Solution 3

xndNode contains an employee object with the Name, AnnualSalary and DaysWorked fields. It's just a matter of converting these into an SQL statment and inserting the row into a table in your database. The details would be database specific, but it should be something like this

insert into employee values (name, annual_salary, days_worked) 

Assuming employees are keyed by name

Share:
35,654
sujeesh
Author by

sujeesh

Updated on February 11, 2020

Comments

  • sujeesh
    sujeesh about 4 years

    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.

  • marc_s
    marc_s about 11 years
    Maybe add a bit of error handling - just in case one of the nodes might not exist ...
  • 4b0
    4b0 about 11 years
    Assuming answer as per his xml doc