Quantcast
Channel: Grouping XElement when generating XML from CSV - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by Jeff Mercado for Grouping XElement when generating XML from CSV

$
0
0

Assuming the first line of the file is always the name, read that line out first, then process the rest as CSV. After reading the rows in, group them by the appropriate column and build out the XML.

XDocument GetXml(string path){    using (var file = File.OpenText(path))    {        var name = file.ReadLine();        return new XDocument(            new XElement("Project",                new XAttribute("Name", name),                from row in ReadRows(file)                group row.Item2 by row.Item1 into g                select new XElement(g.Key,                    from r in g                    select new XElement(r)                )            )        );    }}IEnumerable<Tuple<string, string>> ReadRows(TextReader file){    using (var reader = new CsvReader(file, new CsvConfiguration { HasHeaderRecord = false, TrimFields = true }))    {        while (reader.Read())            yield return Tuple.Create(reader.GetField(0), reader.GetField(1));    }}

Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>