Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hai to all,


I want to convert xml file into csv format in web application.How can i do.I tried lot.But after clicking a button it going straightly into excelsheet only but not csv.plz help me

Below is the sample code.
 //sample.xml
  <authors_table>
  <authors>
    <au_id>172-32-1176</au_id>
    <au_lname>White</au_lname>
    <au_fname>Johnson</au_fname>
    <phone>408 496-7223</phone>
    <address>10932 Bigge Rd.</address>
    <city>Menlo Park</city>
    <state>CA</state>
    <zip>94025</zip>
    <contract>true</contract>
  </authors>
<authors_table></authors_table></authors_table>


output as
172-32-1176,white,johnson,408 496-7223,10932 Bigge Rd.,Menlo Park,CA,94025,true
Posted
Updated 28-Dec-21 19:03pm
v3

if I understand correctly, you already have the implementation to convert xml to csv, right?

Do you mean that your output csv file gets opened up in Excel? The reason for that is that you have default program for opening csv files set to Excel.
 
Share this answer
 
v2
Comments
sridharan28 22-Mar-11 6:15am    
will u plz tell me any suitable link for this?
avigodse 22-Mar-11 9:50am    
Just Right-Click on the file in file browser and Select 'Open With' from context menu; and from Popped list, select 'Notepad' like any text editor.
You never "convert" it. No matter how you do it you loose some information.

—SA
 
Share this answer
 
The following method would exactly suffice your requirement.
As I faced the same issue and happen to write the following code to get what I needed.

This converts the DataSet to XML and then to text/csv as you can see. There are few other ContentTypes that you may use to get what's required.

XML File:

XML
<NewTable>
     <Table>
          <a1>12345</a1>
          <a2>12345</a2>
          <a3>12345</a3>
          <a4>12345</a4>
          <a5>12345</a5>
     </Table>
</NewTable>


Function:

C#
protected string ConvertToCSV(DataSet objDataSet)
{
        string xmlInput = objDataSet.GetXml();
        string csvOut = string.Empty;
        XDocument doc = XDocument.Parse(xmlInput);
        StringBuilder sb = new StringBuilder(100000);
        foreach (XElement node in doc.Descendants("Table"))
        {
            foreach (XElement innerNode in node.Elements())
            {
                //"{0}," give you the output in Comma seperated format.
                sb.AppendFormat("{0},", innerNode.Value);
            }
            sb.Remove(sb.Length - 1, 1);
            sb.AppendLine();
        }
        csvOut = sb.ToString();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.ContentType = "text/csv";
        Response.ContentEncoding = Encoding.GetEncoding(0);
        Response.AppendHeader("Content-Disposition", "attachment;filename=Report.csv");
        Response.Output.Write(csvOut);
        Response.End();
        return csvOut;
}
 
Share this answer
 
v2
public static void ConvertToCsv(string SourceFilePath)
       {
           FileInfo fi = new FileInfo(SourceFilePath);

           string FileName = fi.Name.Split('.')[0].ToString();
           string directoryName = fi.DirectoryName + "\\";
           string extn = fi.Extension;

           DataSet ds = new DataSet();

           ds.ReadXml(SourceFilePath);

           string XmlFileDate = FileName.Split('_')[0].ToString();
           string XmlFolderPath = directoryName + XmlFileDate;

           StringBuilder sb = new StringBuilder();

           foreach (DataTable dt in ds.Tables)
           {
               foreach (DataColumn col in dt.Columns)
               {
                   if (col.DataType == typeof(string))
                       sb.Append(dt.TableName + "_" + col.ColumnName + ", ");
               }
           }
           sb.Append(Environment.NewLine);

           foreach (DataTable dt in ds.Tables)
           {
               foreach (DataRow row in dt.Rows)
               {
                   for (int i = 0; i < dt.Columns.Count; i++)
                   {
                       if (dt.Columns[i].DataType == typeof(string))
                       {
                           string sRowVal = row[i].ToString().Replace("\r\n", " ");
                           sb.Append(sRowVal + ", ");
                       }

                   }
               }
           }
           sb.Remove(sb.Length - 2, 1);
           sb.Append(Environment.NewLine);

           File.WriteAllText(XmlFolderPath + "\\" + XmlFileDate + ".csv", sb.ToString());
       }
 
Share this answer
 
Comments
CHill60 29-Dec-21 4:39am    
When adding yet another solution to such an old post, it would be a good idea to add some commentary explaining why your solution is an improvement on what has already been posted.
Your solution is somewhat confusing as you have left in your code to handle an assumed filename format.
Also - why are you only outputting string data?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900