Convert CSV to XML in C#

CSV and XML are among the most popular file formats used by developers. These formats are normally used to store and exchange data within and between applications. It is often required to convert one format into another before storing or transmitting the information. In this article, you will find how to programmatically convert the CSV (comma-separated values) file into XML format using C#.

Convert CSV to XML using CSharp

The article covers the following topics:

.NET API for CSV to XML Conversion

GroupDocs.Conversion provides APIs that allow the CSV and XML files conversions. In this article, we will use the .NET API of GroupDocs.Conversion for converting the CSV format data into XML format using C#. Additionally, the API supports many other file formats for conversion like word-processing documents, spreadsheets, presentations, eBooks, images, etc.

You can download the DLLs or MSI installer from the downloads section or install the API in your .NET application via NuGet.

PM> Install-Package GroupDocs.Conversion

Convert CSV to XML in C#

The CSV files can be viewed and visually edited using editors like MS Excel. The image shows the CSV data that I have used for the conversion. There are many CSV to XML converters available online, however, the code mentioned in this section can empower your .NET applications with this simple conversion.

CSV Sample file opened in Excel

The following steps guide you to convert the provided data of CSV format into XML format.

  • Load the CSV file using the Converter class.
  • Set the conversion format as XML using the DataConvertOptions.
  • Call the Convert method to get the XML format data from the loaded CSV file.

The following source code converts the CSV file to XML format using C#.

The output of the above code is as follows. I am sharing the part of the XML file for you to get an idea of the XML output.

<DocumentElement>
  <Sheet1>
    <Employee>David</Employee>
    <Quarter>1</Quarter>
    <Product>Maxilaku</Product>
    <Continent>Asia</Continent>
    <Country>China</Country>
    <Sale>2000</Sale>
  </Sheet1>
  <Sheet1>
    <Employee>David</Employee>
    ...
  </Sheet1>
  <Sheet1>
    ...
  </Sheet1>
</DocumentElement>

Get a Free API License

You can get a free temporary license to use the API without the evaluation limitations.

Conclusion

To sum up, we discussed the conversion of CSV data into XML format within the .NET applications using C#. To build your own conversion app, you may learn more about the Conversion Automation .NET API using the documentation. The best is to experience the examples available on GitHub. Contact us for any query via the forum.

See Also