Transforms a CSV (Comma-Separated Values) file into an XML document.

Code (C#)

// Clear the output editor

// Create XML document
XmlDocument xmlDoc = new XmlDocument();

// Add XML declaration tag: <?xml>
XmlDeclaration xmlNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

// Add root node: <CsvToXml>...</CsvToXml>
XmlElement csvNode = xmlDoc.CreateElement("CsvToXml");

// Generate column names for use in the XML document
string[] columnNames = new string[Input.Columns.Count];
for (int colIndex = 0; colIndex < Input.Columns.Count; colIndex++)
    // If available, use the given column title
    columnNames[colIndex] = (Input.HeaderRow != null ? Input.HeaderRow[colIndex] : "");
    // If no column title is given, generate a new one
    if (columnNames[colIndex] == "")
        columnNames[colIndex] = "Field" + colIndex.ToString();
    // Make sure that the column name is a valid XML name
    columnNames[colIndex] = XmlConvert.EncodeName(columnNames[colIndex]);

// Add node for every row in the CSV document
foreach(ICsvRow row in Input.BodyRows)
    // <Row>...</Row>
    XmlElement rowNode = xmlDoc.CreateElement("Row");
    // Add sub node for each available cell in the row
    for (int colIndex = 0; colIndex < row.Cells.Count; colIndex++)
        // <ColumnName>...</ColumnName>
        XmlElement cellNode = xmlDoc.CreateElement(columnNames[colIndex]);

// Write XML content to StringWriter
using (StringWriter stringWriter = new StringWriter())
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter))
    xmlTextWriter.Formatting = Formatting.Indented;  // Output formatted XML code
    // Output XML code
    Output.Text = stringWriter.ToString();
Input Type: CSV, Output Type: Plain Text

Download Project File

File: Convert_CSV_to_XML.dvp (15.47 KB)

To open this file, DataVoila must be installed on your computer. If this is not yet the case, please click here to download the free demo version.