We had a requirement where the input file coming from the customer was XML but it was supposed to be executed through an external application which accepted CSV file.
So, in this blog post I will cover how to read data from XML and then store them to CSV file.
It is written using C# and following were referenced.
using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.IO;
XDocument xDoc_new = XDocument.Load(fileName); // input filename
var results = xDoc_new.Descendants(“PurchaseOrder”).Select(x => new
{ //PurchaseOrder Node
poId = (string)x.Attribute(“id”), // Inner attribute
header = x.Descendants(“Header”).Select(y => new
{
accountNumber = (string)y.Element(“AccountNumber”),
shipDate = (string)y.Element(“ShipDate”)
}).ToList(),
itemList = x.Descendants(“Item”).Select(z => new
{
itemNumber = (string)z.Element(“ItemNumber”),
uom = (string)z.Element(“UM”),
price = (decimal)z.Element(“Price”),
quantity = (int)z.Element(“Quantity”)
}).ToList()
}).ToList();
// Create array here to store the results into an array and use it below.
{ //Build CSV File.
Int16 iCnt = 0, errorCount = 0;
string headerData = getHeader(); //it has the header data (not shown here).
try
{
using (var stream = new FileStream(csvFile, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(stream))
{
foreach (Helper.XML_Items item in ItemsInFeed)
{
if (iCnt == 0) //write header data once
{
writer.Write(headerData);
writer.WriteLine();
}
writer.Write(poID + delimit);
writer.Write(poDate + delimit);
writer.Write(item.ItemNr + delimit); //SMA SKU
writer.Write(item.Quantity.ToString() + delimit); //Qty
writer.Write(item.Price.ToString() + delimit); //Base Price
writer.WriteLine();
iCnt++;
}
}
}
catch (Exception ex)
{// do error handling her.
errorCount++;
}
}
Feel free to contact us for any questions.