如何将.tsv内容转换为xml

时间:2019-04-26 11:59:39

标签: c# csv

我有一个tsv文件,看起来像下面的

Time    Object  pmPdDrb pmPdcDlSrb
00:45   EUtranCellFDD=GNL02294_7A_1 2588007 1626
00:45   EUtranCellFDD=GNL02294_7B_1 18550   32
00:45   EUtranCellFDD=GNL02294_7C_1 26199   38
00:45   EUtranCellFDD=GNL02294_9A_1 3857243 751

是否可以像下面这样将其转换为XML?

<xmlnode>
  <Time>00:45</Time>
  <Object>EUtranCellFDD=GNL02294_7A_1</Object>
  <pmPdDrb>2588007</pmPdDrb>
  <pmPdcDlSrb>1626</pmPdcDlSrb>
</xmlnode>

我尝试了以下代码:

var reader = File.ReadAllLines(logFile);

var xml1 = new XElement("TopElement",

reader.Select(line => new XElement("Item",

    line.Split('\t').Select((column, index) =>

         new XElement("Column" + index,column)))
    )
);

1 个答案:

答案 0 :(得分:1)

尝试以下操作:

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

namespace ConsoleApplication110
{
    class Program
    {
        const string INPUT_FILENAME = @"c:\temp\test.txt";
        const string OUTPUT_FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string header = "<xmlnodes></xmlnodes>";

            XDocument doc = XDocument.Parse(header);
            XElement xmlnodes = doc.Root;

            StreamReader reader = new StreamReader(INPUT_FILENAME);

            string line = "";
            string[] columnNames = null;
            int lineCount = 0;
            while((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (line.Length > 0)
                {
                    string[] splitArray = line.Split(new char[] { '\t', ' '}, StringSplitOptions.RemoveEmptyEntries);
                    if (++lineCount == 1)
                    {
                        columnNames = splitArray;
                    }
                    else
                    {
                        XElement newNode = new XElement("xmlnode");
                        xmlnodes.Add(newNode);
                        for(int i = 0; i < splitArray.Length; i++)
                        {
                            XElement xColumn = new XElement(columnNames[i], splitArray[i]);
                            newNode.Add(xColumn);
                        }

                    }
                }
            }

            doc.Save(OUTPUT_FILENAME);

        }

    }


}