Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through XML document

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.

like image 981
sujeesh Avatar asked Feb 11 '13 05:02

sujeesh


People also ask

Can you loop in XML?

An XML document (or a section of an XML document) is passed into the For Each loop in a business process variable. An iteration variable holds the current element being processed in the For Each loop, for the life of the loop. This section describes how to add this looping logic to your business process.

What is loop element in XML?

MS XML connectors The loop element allows you to define the iterating object. Generally the Loop element is also the row generator.


2 Answers

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;
}
like image 194
4b0 Avatar answered Oct 21 '22 09:10

4b0


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

like image 32
masterlopau Avatar answered Oct 21 '22 07:10

masterlopau