I have a case, in c#, where i read an xml file with variable number of specific objects in the form of
<car> <carType>some-type</carType> <objects> <object> <id>1</id> <name>wheel</name> </object> <object> <id>2</id> <name>engine</name> </object> </objects> </car>
and i need to pass the name in a pivot table in an excel file. The problem is that according to a car type tag there will be a different excel and different types and number of objects.
Is there a design pattern to make this more dynamic and not use a switch or if statement and every time a new car type appears not be necessary to update the code?
using Xml Linq you can create a pivot table using code below :
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication1 { class Program { const string FILENAME = @"c:\temp\test.xml"; static void Main(string[] args) { XDocument doc = XDocument.Load(FILENAME); string[] columnNames = doc.Descendants("id") .Select(x => (string)x) .Distinct() .OrderBy(x => x) .ToArray(); DataTable pivot = new DataTable(); pivot.Columns.Add("carType", typeof(string)); foreach (string columnName in columnNames) { pivot.Columns.Add(columnName, typeof(string)); } foreach (XElement car in doc.Descendants("car")) { DataRow row = pivot.Rows.Add(); row["carType"] = (string)car.Element("carType"); foreach (XElement obj in car.Descendants("object")) { string id = (string)obj.Element("id"); string name = (string)obj.Element("name"); row[id] = name; } } } } }