C#newbie中的XML到CSV

时间:2015-06-29 10:52:35

标签: c# xml csv

Hello Guys我需要有关此xml数据的帮助。

arr[0] = substr("20160101", 0, 4);
arr[1] = substr("20160101", 4, 2);
arr[2] = substr("20160101", 6, 2);

我想使用knre1,knre2和“betrag”id来编写csv数据。它总是一样的名字。 应该看起来像这样

AT; U18713701; 7605

我是c#的新手,我需要帮助。

2 个答案:

答案 0 :(得分:0)

这是非常基本的事情:

using System.Xml.XPath;
using System.Xml.Linq;
using System.IO;

XDocument xdoc = XDocument.Load("test.xml");
StringBuilder csv = new StringBuilder();

foreach (XElement datarow in xdoc.Root.XPathSelectElements("dataset/datarow"))
{
    string knre1 = datarow.Elements("element").Where(i => i.Attribute("id").Value.Contains("knre1")).First().Value;
    string knre2 = datarow.Elements("element").Where(i => i.Attribute("id").Value.Contains("knre2")).First().Value;
    string betrag = datarow.Elements("element").Where(i => i.Attribute("id").Value.Contains("betrag")).First().Value;

    csv.AppendLine(knre1 + "," + knre2 + "," + betrag);
}

File.WriteAllText("cvsFile.csv", csv.ToString());

答案 1 :(得分:0)

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();


        XDocument xdoc = XDocument.Load("C:\\Users\\edvazubi\\Desktop\\ZM05.2015.xml");
        StringBuilder csv = new StringBuilder();

        foreach (XElement datarow in xdoc.Root.XPathSelectElements("instance/dataset/datarow"))
        {


            string knre1 = datarow.Elements("element").Where(i => i.Attribute("id").Value.Contains("knre1")).First().Value;
            string knre2 = datarow.Elements("element").Where(i => i.Attribute("id").Value.Contains("knre2")).First().Value;
            string betrag = datarow.Elements("element").Where(i => i.Attribute("id").Value.Contains("betrag")).First().Value;



            csv.AppendLine(knre1 + "," + knre2 + "," + betrag + "L");
        }

        File.WriteAllText("C:\\Users\\edvazubi\\Desktop\\CSVFile.csv", csv.ToString());

这是我的档案