I'm pretty sure this code can be optimized, but I'm not talented enough in Linq to do it myself. Here's what I'm trying to do: I have an XML file that needs to be converted into a .csv file. The XML looks like this:
<Inventory>
<Item>
<Name>Super Mario Bros</Name>
<Count>14</Count>
<Price>29,99</Price>
<Comment>-No Comment-</Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1985</Year>
<ProductID>001</ProductID>
</Item>
<Item>
<Name>The Legend of Zelda</Name>
<Count>12</Count>
<Price>34,99</Price>
<Comment>-No Comment-</Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1986</Year>
<ProductID>002</ProductID>
</Item>
</Inventory>
(There are many more Items in the list, but they are all the same.)
The code I'm currently using is working as intended, here it is:
public void fileConvert_XMLToCSV() {
//This method converts an xml file into a .csv file
XDocument xDocument = XDocument.Load(FilePath_CSVToXML);
StringBuilder dataToBeWritten = new StringBuilder();
var results = xDocument.Descendants("Item").Select(x => new {
title = (string)x.Element("Name"),
amount = (string)x.Element("Count"),
price = (string)x.Element("Price"),
year = (string)x.Element("Year"),
productID = (string)x.Element("ProductID")
}).ToList();
for (int i = 0; i < results.Count; i++) {
string tempTitle = results[i].title;
string tempAmount = results[i].amount;
string tempPrice = results[i].price;
string tempYear = results[i].year;
string tempID = results[i].productID;
dataToBeWritten.Append(tempYear);
dataToBeWritten.Append(";");
dataToBeWritten.Append(tempTitle);
dataToBeWritten.Append(";");
dataToBeWritten.Append(tempID);
dataToBeWritten.Append(";");
dataToBeWritten.Append(tempAmount);
dataToBeWritten.Append(";");
dataToBeWritten.Append(tempPrice);
dataToBeWritten.Append(";");
dataToBeWritten.Append(0);
dataToBeWritten.Append(";");
dataToBeWritten.Append(0);
dataToBeWritten.Append(Environment.NewLine);
}
Console.WriteLine(dataToBeWritten.ToString());
Console.ReadLine();
var testpath = AppDomain.CurrentDomain.BaseDirectory + @"frMediaShop\test.csv";
File.WriteAllText(testpath, dataToBeWritten.ToString());
}
Running this method outputs a file (test.csv) that looks just like I want it. But the code is repetitive and dull. Please help me optimize it.