首页 > 解决方案 > 如何将 .tsv 内容转换为 xml

问题描述

我有一个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)))
    )
);

标签: c#csv

解决方案


尝试以下:

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);

        }

    }


}

推荐阅读