Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert CSV file to XML

Tags:

c#

xml

csv

I need to Convert a CSV into an XML document. The examples I have seen so far, all show how to do this with a fixed number of columns in the CSV.

I have this so far, using LINQ:

String[] File = File.ReadAllLines(@"C:\text.csv");

        String xml = "";

        XElement top = new XElement("TopElement",

        from items in File

        let fields = items.Split(';')

        select new XElement("Item",

        new XElement("Column1", fields[0]),

        new XElement("Column2", fields[1]),

        new XElement("Column3", fields[2]),

        new XElement("Column4", fields[3]),

        new XElement("Column5", fields[4])

        )

        );

        File.WriteAllText(@"C:\xmlout.xml", xml + top.ToString());

This is for a fixed amount of columns, but my .CSV has a different number of columns on each line.

How would you fit some sort of loop into this, depending on how many words (columns) there are in each line of the .CSV?

Thnx

like image 540
Soeren Avatar asked Jun 18 '10 12:06

Soeren


People also ask

How do I convert a CSV file to XML?

How to convert a CSV to a XML file? Choose the CSV file that you want to convert. Select XML as the the format you want to convert your CSV file to. Click "Convert" to convert your CSV file.

How do I create an XML Schema from a CSV file?

File -> Import -> Text File.Browse for the . csv file and press OK. You will obtain the Import criteria dialog that allows you to choose the field delimiter from the CSV and customize the form of the destination XML file(Change labels).

How do I convert an Excel file to XML?

Click File > Save As, and select the location where you want to save the file. , point to the arrow next to Save As, and then click Other Formats. In the File name box, type a name for the XML data file. In the Save as type list, click XML Data, and click Save.

Is CSV and XML the same?

CSV is considered a flat structure of data format. It is highly convenient because it requires fewer technical skills and you can access files of this format with most applications. Additionally, CSV is significantly smaller than XML, requiring less processing power.


1 Answers

var lines = File.ReadAllLines(@"C:\text.csv");

var xml = new XElement("TopElement",
   lines.Select(line => new XElement("Item",
      line.Split(';')
          .Select((column, index) => new XElement("Column" + index, column)))));

xml.Save(@"C:\xmlout.xml");

Input:

A;B;C
D;E;F
G;H

Output:

<TopElement>
  <Item>
    <Column0>A</Column0>
    <Column1>B</Column1>
    <Column2>C</Column2>
  </Item>
  <Item>
    <Column0>D</Column0>
    <Column1>E</Column1>
    <Column2>F</Column2>
  </Item>
  <Item>
    <Column0>G</Column0>
    <Column1>H</Column1>
  </Item>
</TopElement>
like image 149
dtb Avatar answered Oct 21 '22 08:10

dtb