public CsvDoc TransformFromMapFile(string xmlMapFile) { XmlDocument doc = new XmlDocument(); doc.Load(xmlMapFile); if (doc.DocumentElement.Name != "CsvMap") { throw new InvalidDataException("Not a CsvMap document"); } CsvDoc csvDoc = new CsvDoc { FirstRow = CsvRow.CreateRow(GetFirstRow(doc)) }; foreach (CsvRow row in Data) { csvDoc.Data.Add(TransformRow(row, doc)); } csvDoc = MergeRowsOn(csvDoc, doc); return(csvDoc); }
private CsvDoc MergeRowsOn(CsvDoc csvDoc, XmlDocument doc) { Dictionary <string, List <CsvRow> > rowsToMerge = new Dictionary <string, List <CsvRow> >(); if (!doc.DocumentElement.HasAttribute("merge_on") || string.IsNullOrWhiteSpace(doc.DocumentElement.Attributes["merge_on"].Value)) { return(csvDoc); } int mergeFieldIndex = csvDoc.FirstRow.Fields.IndexOf(doc.DocumentElement.Attributes["merge_on"].Value); if (mergeFieldIndex == -1) { throw new InvalidDataException($"MergeRowsOn() failed to find index of Field {doc.DocumentElement.Attributes["merge_on"].Value} in {csvDoc.FirstRow}"); } foreach (CsvRow row in csvDoc.Data) { if (rowsToMerge.Keys.Contains(row.Fields[mergeFieldIndex])) { rowsToMerge[row.Fields[mergeFieldIndex]].Add(row); } else { List <CsvRow> list = new List <CsvRow>(); list.Add(row); rowsToMerge.Add(row.Fields[mergeFieldIndex], list); } } CsvDoc mergedDoc = new CsvDoc { FirstRow = csvDoc.FirstRow }; foreach (var kvp in rowsToMerge) { mergedDoc.Data.Add(MergeRows(kvp.Value)); } return(mergedDoc); }
static int Main(string[] args) { if (args.Length != 3) { Console.Error.WriteLine("Incorrect number of arguments."); PrintUsage(); #if DEBUG Console.ReadKey(); #endif return(-1); } try { Console.Out.WriteLine($"Loading {args[0]} ..."); CsvDoc source = new CsvDoc(args[0]); Console.Out.WriteLine($"Source csv file has {source.NumColumns} columns and {source.Data.Count} rows excluding the first row."); Console.Out.WriteLine("Mapping ..."); CsvDoc target = source.TransformFromMapFile(args[2]); Console.Out.WriteLine($"Writing to file: {args[1]} ..."); target.WriteToFile(args[1]); Console.Out.WriteLine($"Target csv file has {target.NumColumns} columns and {target.Data.Count} rows excluding the first row."); } catch (Exception ex) { Console.Error.WriteLine("Exception caught:"); Console.Error.WriteLine(ex.ToString()); Console.Error.WriteLine("Terminating"); #if DEBUG Console.ReadKey(); #endif return(-1); } #if DEBUG Console.ReadKey(); #endif return(0); }