Convert CSV to XML when CSV contains character and number data

From this thread, I got basic information on how to parse CSV to create XML. Unfortunately, text fields (all enclosed in quotation marks) sometimes contain commas, so line.split (',') gives me too many columns. I can't figure out how to parse CSV, so line.split (',') distinguishes between commas in the text box and fields that separate commas. Any thoughts on how to do this?

Thank!

+3
source share
6 answers

Grab this code: http://geekswithblogs.net/mwatson/archive/2004/09/04/10658.aspx

.Split( "," ) SplitCSV (), :

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

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

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

, , , Linq, .

+2

FileHelpers.

FileHelpers - .NET / , .

+1

"|"? CSV, - .

0

CSV , , . Office ACE OLEDB , . , .

0

, , .

, :

"first name","last name","phone number"
"john,jane","doe","555-5555"

:

string csv = GetCSV();  // will load your CSV, or the above data
foreach (string  line in csv.Split('\n'))
{
    Console.WriteLine("--- Begin record ---");
    foreach (Match m in Regex.Matches(line, "\".+?\""))            
        Console.WriteLine(m.Value);            
}

:

--- Begin record ---
"first name"
"last name"
"phone number"
 --- Begin record ---
"john,jane"
"doe"
"555-5555"

Regex, csv 2 .
, XML.

0

, Regex. ","

, :

line.Split("\",\"")

.

0

Source: https://habr.com/ru/post/1777556/


All Articles