c# - 如何将 .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)))
)
);
解决方案
尝试以下:
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);
}
}
}
推荐阅读
- swift - SwiftUI:如何使图像与列表中的屏幕边缘齐平?
- r - 如何修复为数据框提供的“无效的‘dimnames’?
- html - 我无法控制的 HTML 中的 ASCII 艺术
- java - 在运行时查找包中的所有类(并调用静态方法)
- javascript - Javascript Set has() 方法的行为因我定义传入参数的方式而异
- docker - 并不总是创建中间容器
- ios - 使用 Combine 和 SwiftUI 显示变化值的最简洁方式是什么?
- regex - 正则表达式在 html 注释中查找和替换字符
- python - 用于守望台的“docker run”命令的 Python 脚本
- android - 如何将 FCM 插入房间数据库?