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

XML to CSV



XmlRecordReader allows you to specify an XPath to loop over any size XML file, and then use additional XPaths to specify nodes and attributes that can then be referenced by name.

In the example below, each call to ReadRecord will advance to the next occurrence of the XPath users/user. It then retrieves the values of the nodes user_id, first_name, and last_name by the names id, first, and last respectively.

The example also shows how simple it is to use CsvWriter to write the values to a properly formatted CSV file.

Both classes are available in the DataStreams framework.

Source 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>
Destination File Format
user_id,first_name,last_name
1,George,Washington
2,Abraham,Lincoln
...
C#
using (CsvWriter writer = new CsvWriter("users.csv"))
using (XmlRecordReader reader = new XmlRecordReader("users.xml", "users/user"))
{
	reader.Columns.Add("user_id", "id");
	reader.Columns.Add("first_name", "first");
	reader.Columns.Add("last_name", "last");

	writer.Write("user_id");
	writer.Write("first_name");
	writer.Write("last_name");
	writer.EndRecord();

	while (reader.ReadRecord())
	{
		writer.Write(reader["id"]);
		writer.Write(reader["first"]);
		writer.Write(reader["last"]);
		writer.EndRecord();
	}

	reader.Close();
	writer.Close();
}