更新-我正在尝试使用C#将大量文本文件(最多3K个文件)转换为XML文件。
我想遵循两个步骤:
2) 使用与*相同的名称。要创建的txt文件*。另一个文件夹中的xml文件。
代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace TxT2XML
{
class Program
{
private static void Main(string[] args)
{
string path = @"C:\Users\wcks\Documents\Visual Studio 2015\Projects\TxT2XML\Data_TXT_Files\";
string[] fileEntries = Directory.GetFiles(path);
Dictionary<string, string[]> dicData = new Dictionary<string, string[]>();
foreach (string fileName in fileEntries)
{
if (!File.Exists(path))
{
string[] contents = new string[100];
string fieldDateLogged = "Date Logged:";
string fieldTaskName = "Task Name:";
string fieldUserID = "User ID:";
var lines = File.ReadAllLines(fileName);
contents[0] = lines.Where(x => x.Contains(fieldDateLogged)).FirstOrDefault().Replace(fieldDateLogged, string.Empty).Trim();
contents[1] = lines.Where(x => x.Contains(fieldTaskName)).FirstOrDefault().Replace(fieldTaskName, string.Empty).Trim();
contents[2] = lines.Where(x => x.Contains(fieldUserID)).FirstOrDefault().Replace(fieldUserID, string.Empty).Trim();
XElement xElem = new XElement(fieldTaskName, dicData.Select(x => new XElement("DataLogName", new XAttribute(fieldTaskName, x.Key), new XAttribute(contents[0], x.Value))));
var xml = xElem.ToString();
Console.Write(xml);
}
}
}
}
}
class DataLogName
{
[XmlAttribute]
public string DataLogged { set; get; }
[XmlAttribute]
public string TaskName { set; get; }
[XmlAttribute]
public string UserID { set; get; }
}
<DataLogName>
<DataLogged>01-01-2017<DataLogged>
<TaskName>Project Name<TaskName>
<UserID>123456<UserID>
<DataLogName>
文本文件示例:
SOFTWARE DATA LOG Data Log
Date Logged: 09-29-2014 02:17:45 PM
Task Name: PROJECT_NAME
User ID: Administrator Mode
System: COMPUTER_XPTO
Machine ID: XXXXXXXX
Device: XXXXXXXXXXXXXX
Data Source: c:\ROOT\FOLDER\X.BIN
Sumcheck: 5DC95067
Process: XXXXXXX/XXXXX/XXXXX/XXXXXX