Friday, 8 November 2013

XML Data to CSV file using C#

Share it Please
Xml Code:-
<Employee>
  <Emp>
    <Name>Mohamed</Name>
    <Age>27</Age>
    <Salary>100000</Salary>
  </Emp>
  <Emp>
    <Name>Raja</Name>
    <Age>26</Age>
    <Salary>200000</Salary>
  </Emp>
  <Emp>
    <Name>uthaya</Name>
    <Age>30</Age>
    <Salary>450000</Salary>
  </Emp>
</Employee>
C# Code:-
MemoryStream ms = new MemoryStream();
            DataSet ds = new DataSet();
            ds.ReadXml(@"E:\Student.xml");
            if (ds.Tables[0].Rows.Count > 0)
            {
                StreamWriter writer = new StreamWriter(ms);
                writer.AutoFlush = true;
                foreach (DataColumn column in ds.Tables[0].Columns)
                {
                    writer.Write(column.ColumnName.ToString() + ",");
                }
                writer.WriteLine();
                foreach (DataRow Drow in ds.Tables[0].Rows)
                {
                    writer.Write(Drow["Name"].ToString() + "," + Drow["Age"] + "," + Drow["Salary"].ToString() + ",");
                    writer.WriteLine();
                }
            }
            using (FileStream file = new FileStream("E:\\Output.csv", FileMode.Create, FileAccess.Write))
            {
                ms.WriteTo(file);
            }

No comments:

Post a Comment

Followers

Follow The Author