Convert XML File To Csv File Format In C#


Answer :

using System.IO;
using System.Xml.Serialization;


You can do like this:



public class Sequence
{
public Point[] SourcePath { get; set; }
}

using (FileStream fs = new FileStream(@"D:\youXMLFile.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(Sequence[]));
var data=(Sequence[]) serializer.Deserialize(fs);
List<string> list = new List<string>();
foreach(var item in data)
{
List<string> ss = new List<string>();
foreach (var point in item.SourcePath) ss.Add(point.X + "," + point.Y);
list.Add(string.Join(",", ss));
}
File.WriteAllLines("D:\\csvFile.csv", list);
}


In an alternate way you can use leverage the power of XSLT to convert it,


Steps



  • Create an Xml stylesheet to convert xml to csv

  • Use XslCompiledTransform() to convert get the csv string

  • save the csv string to a file


You may came up with an Xslt like this, call it data.xsl


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="UTF-8"/>
<xsl:template match="/">
<xsl:for-each select="//Point">
<xsl:value-of select="X"/>,<xsl:value-of select="Y"/>
<xsl:text>&#xD;&#xA;</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

and use the following method


public static string ToCSV(string xmlTextDate, string xsltFile)
{
string result = string.Empty;
var xpathDoc = new XPathDocument(xmlTextDate);
var xsltTransform = new System.Xml.Xsl.XslCompiledTransform();
xsltTransform.Load(xsltFile);

using (MemoryStream ms = new MemoryStream())
{
var writer = new XmlTextWriter(ms, Encoding.UTF8);
using (var rd = new StreamReader(ms))
{
var argList = new System.Xml.Xsl.XsltArgumentList();
xsltTransform.Transform(xpathDoc, argList, writer);
ms.Position = 0;
result = rd.ReadToEnd();
}
}
return result;
}

and call it like this


var csvString = ToCSV("yourfile.xml","data.xsl");


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable