使用多个集合将XML转换为c#中的csv

问题描述

我正在寻找一种将xml流转换为csv的方法,但是我只找到1个集合的解决方案,即我的xml看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<CompactData>
<Header>
<ID>id_ofç=_file</ID>
<Test>false</Test>
</Header>
<data:DataSet>
<data:Series FREQ="M" item="item1" unit="unit1">
<data:Obs TIME_PERIOD="2015-01" OBS_VALUE="5.47" />
<data:Obs TIME_PERIOD="2015-02" OBS_VALUE="5.01" />
<data:Obs TIME_PERIOD="2015-03" OBS_VALUE="5.39" />
</data:Series>
<data:Series FREQ="M" item="item2" unit="unit2">
<data:Obs TIME_PERIOD="2015-01" OBS_VALUE="5.47" />
<data:Obs TIME_PERIOD="2015-02" OBS_VALUE="5.01" />
<data:Obs TIME_PERIOD="2015-03" OBS_VALUE="5.39" />
</data:Series>
</data:DataSet>
</CompactData>

在这里,我要使用以下格式的csv:

FREQ,item,unit,TIME_PERIOD,OBS_VALUE

什么是最好的方法? 谢谢!

解决方法

尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication166
{
    class Program
    {
        const string XML_FILENAME = @"c:\temp\test.xml";
        const string CSV_FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            StreamWriter writer = new StreamWriter(CSV_FILENAME);
            writer.WriteLine(string.Join(",",new string[] {"FREQ","item","unit","TIME_PERIOD","OBS_VALUE"}));


            XDocument doc = XDocument.Load(XML_FILENAME);

            XElement dataSet = doc.Descendants().Where(x => x.Name.LocalName == "DataSet").FirstOrDefault();
            XNamespace nsData = dataSet.GetNamespaceOfPrefix("data");

            foreach (XElement series in dataSet.Elements(nsData + "Series"))
            {
                string freq = (string)series.Attribute("FREQ");
                string item = (string)series.Attribute("item");
                string unit = (string)series.Attribute("unit");
                foreach (XElement obs in series.Elements(nsData + "Obs"))
                {
                    DateTime time = DateTime.ParseExact((string)obs.Attribute("TIME_PERIOD"),"yyyy-MM",System.Globalization.CultureInfo.InvariantCulture);
                    double value = (double)obs.Attribute("OBS_VALUE");
                    writer.WriteLine(string.Join(",new string[] {freq,item,unit,time.ToString(),value.ToString()}));
                }
            }

            writer.Flush();
            writer.Close();
        }
    }
 
}