Convert XML file to csv file format in c#

Sohaib Omar picture Sohaib Omar · Feb 25, 2016 · Viewed 26.9k times · Source

I am using accord.net mouse gesture recognition sample application, which saves the file in above xml format. I need help to convert above xml in to CSV format so i can do machine learning using accord.net Dynamic time warping. I can not figure out how to convert in to csv file.

For example: 261,210,261,214,261,229,261,231

<?xml version="1.0"?>
<ArrayOfSequence xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Sequence>
    
    <SourcePath>
      <Point>
        <X>261</X>
        <Y>210</Y>
      </Point>
      <Point>
        <X>261</X>
        <Y>214</Y>
      </Point>
      <Point>
        <X>261</X>
        <Y>227</Y>
      </Point>
      <Point>
        <X>261</X>
        <Y>229</Y>
      </Point>
      <Point>
        <X>261</X>
        <Y>231</Y>
      </Point>
      <Point>
        <X>261</X>
        <Y>234</Y>
      </Point>
      <Point>
        <X>261</X>
        <Y>237</Y>
      </Point>
</Sequence>
</ArrayOfSequence>

Answer

Tuyen Pham picture Tuyen Pham · Feb 25, 2016
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);
}