I’ve a csv file that contains the records below:
Col1,Col2,Col3
“Test,Test1”,1,3
And I’ve Linq query below which splits the csv to XML document. However, for given example above it’s spliting the “Test,Test1” in to two separate element.
var xml = new XElement("Root", source.Select(x =>
new XElement("Testing", x.Split(splitChar).Select((Field, index) =>
new XElement("Field" + index, Field)))).Skip(1));
This generates something like:
<Root>
<Testing Field0="Test" Field01="Test1" Field02="1" Field03="3" />
</Root>
But what i want is:
<Root>
<Testing Field0="Test,Test1" Field01="1" Field02="3" />
</Root>
Could anyone please help me achive above?
Instead of this:
try this approach using a regular expression:
This matches either a field that is quoted, for example:
"foobar,baz"or something that doesn’t contain a comma.There are some limitations with my answer:
"Test1,Test\"two\",Test3",0,1. Do you need this?Regex.Escapeif you want to build the regular expression based on the runtime value ofsplitChar.