Home > Code Samples > Convert CSV to XML in C#

CSV to XML



Source File Format
user_id,first_name,last_name
1,George,Washington
2,Abraham,Lincoln
...
Destination File Format
<?xml version="1.0" encoding="utf-8" ?> 
<users>
	<user>
		<user_id>1</user_id> 
		<first_name>George</first_name> 
		<last_name>Washington</last_name> 
	</user>
	<user>
		<user_id>2</user_id> 
		<first_name>Abraham</first_name> 
		<last_name>Lincoln</last_name> 
	</user>
	...
</users>
C#
XmlTextWriter writer = new XmlTextWriter("users.xml", Encoding.UTF8);

writer.WriteStartDocument();
writer.WriteStartElement("users");

using (CsvReader reader = new CsvReader("users.csv"))
{
	reader.ReadHeaders();

	while (reader.ReadRecord())
	{
		writer.WriteStartElement("user");

		writer.WriteElementString("user_id", reader["user_id"]);
		writer.WriteElementString("first_name", reader["first_name"]);
		writer.WriteElementString("last_name", reader["last_name"]);

		writer.WriteEndElement();
	}

	reader.Close();
}

writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();