Convert CSV to XML in Asp.Net using StreamReader and DataTable in C# and VB

Just a day before, I have shared a post with an example explaining how to read data from a CSV file in Asp.Net. Now I am extending that example and here in this post I’ll show you an example in C# and Vb.Net on how to convert a CSV file to an XML file in Asp.Net using StreamReader and DataTable class.

Convert CSV to XML in Asp.Net C# using StreamRead and DataTable

Related: How to Bind Data Dynamically to an HTML5 Datalist using Asp.Net DataTable - C# and Vb.Net

Create XML File using DataTable WriteXML() Method

The DataTable class in Asp.Net provides a method called WriteXML(). The method takes a parameter in the form a filename along with the path, where you want to save the XML file. I am using this method in my example here.

DataTable.WriteXml()

Along with the WriteXML() method, I am using few other methods in the DataTable class. See the code below.

Read CSV File using Asp.Net StreamReader

To extract data from CSV file, you will have to use the StreamReader class. I have explained about this class before

Now lets see the code.

Code Behind (C#)

I have a CSV file (with .txt) extension, saved in my D: Drive. I have few rows of data, each separated by a comma. See the above image.

using System;
using System.IO;            // FOR StreamReader.
using System.Data;          // FOR DataTable AND DataColumn.

public partial class SiteMaster : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // BE CAREFULL WITH Backward and forward SLASH IN FILE PATH.
        convertCSV_to_XML("d:/birds.txt");
    }

    private void convertCSV_to_XML(string sfileName)
    {
        // CREATE AN INSTANCE OF StreamReader TO READ THE FILE.
        using (StreamReader sr = new StreamReader(sfileName))
        {
            DataTable mytable = new DataTable();

            mytable.TableName = "Birds";    // FOR Birds TAG IN XML.

            DataColumn tColumn = null;      // TABLE COLUMNS.
	
            // CREATE THREE COLUMNS.
            tColumn = new System.Data.DataColumn("Code", System.Type.GetType("System.String"));
            mytable.Columns.Add(tColumn);

            tColumn = new System.Data.DataColumn("Name", System.Type.GetType("System.String"));
            mytable.Columns.Add(tColumn);

            tColumn = new System.Data.DataColumn("Type", System.Type.GetType("System.String"));
            mytable.Columns.Add(tColumn);

            do
            {
                string s = sr.ReadLine();           // READ LINE OF CHARACTERS FROM THE STREAM.
                string[] arrData = s.Split(',');    // STORE VALUES IN THE ARRAY.

                mytable.Rows.Add(arrData);

            } while (!(sr.EndOfStream));

            mytable.WriteXml("d:/birds.xml");       // WRITE DataTable TO AN XML FILE.
            mytable.Dispose();                      // RELEASE MEMORY.
        }
    }
}

Using StreamReader, I am extracting and reading data my CSV file. Next, I am creating an instance of DataTable class. My table has name called Birds. See the tags in the XML file.

I am creating three columns using the DataColumn object and adding the columns to my DataTable object. Finally, inside the Do loop I am extracting the CSV data one by one and adding it to my DataTable object as rows.

mytable.Rows.Add(arrData);

After I have created and added rows to the DataTable, I am using the WriteXML() method to write the table data in XML file.

mytable.WriteXml("d:/birds.xml");

Also Read: Export Data to Excel (Showing Running Total) using Asp.Net DataTable and DataGrid – C#, Vb.Net

Code Behind (Vb.Net)
Option Explicit On
Imports System.Data                 ' FOR DataTable AND DataColumn.
Imports System.IO                   ' FOR StreamReader.

Partial Class Site
    Inherits System.Web.UI.MasterPage

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        convertCSV_to_XML("d:/birds.txt")
    End Sub

    Private Sub convertCSV_to_XML(ByVal sfileName As String)
        ' CREATE AN INSTANCE OF StreamReader TO READ THE FILE.
        Using sr As New StreamReader(sfileName)

            ' CREATE AN INSTANCE OF A DataTable CLASS.
            Dim myTable As DataTable = New DataTable

            With myTable
                .TableName = "Birds"

                Dim tColumn As Data.DataColumn          ' TABLE COLUMNS.

                tColumn = New Data.DataColumn("Code", System.Type.GetType("System.String"))
                myTable.Columns.Add(tColumn)

                tColumn = New Data.DataColumn("Name", System.Type.GetType("System.String"))
                myTable.Columns.Add(tColumn)

                tColumn = New Data.DataColumn("Type", System.Type.GetType("System.String"))
                myTable.Columns.Add(tColumn)

                Do
                    Dim arrData() As String = sr.ReadLine.Split(",")        ' SPLIT AND STORE VALUES IN THE ARRAY.

                    .Rows.Add(arrData)          ' ADD ROWS TO THE DataTable.

                Loop Until sr.EndOfStream

                .WriteXml("d:/birds.xml")       ' WRITE DataTable TO AN XML FILE.
                .Dispose()                      ' RELEASE MEMORY.
            End With
        End Using
    End Sub
End Class

Well, That’s it. Thanks for reading.

Previous - How to Read Data from a CSV File in Asp.Net using StreamReader Class in C# and VB.Net



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!