固定文件到对象数组的位置配置在xml
本文关键字:位置 配置 xml 数组 文件 对象 | 更新日期: 2023-09-27 18:02:32
我想将一个固定长度的文件转换为c#对象。例如,我有一个固定长度的文件,如
Input File
------------
SAM DENVER 20
temp texas 33
表示姓名、地点、年龄、长度为10的姓名、长度为10的地点、长度为2的年龄。
现在我正在为输入文件
中的位置配置xmlXML配置
<Mapping>
<Name StartPosition ="1" Length ="10"></Name>
<Place StartPosition ="11" Length ="10"></Place>
<Age StartPosition ="21" Length ="2"></Age>
</Mapping>
我有一个类,像
类对象public class InputFileConvertor
{
public string Name{get;set;}
public string Place{get;set;}
public string Age{get;set;}
}
public class InputFileConvertor
{
public string Name{get;set;}
public string Place{get;set;}
public string Age{get;set;}
}
现在我的问题是如何将这个输入固定长度的文件与n条记录转换为InputFileConvertor的字符串数组。它应该在XML文件中接受所有预配置的参数。
注意:我希望以更少的内存消耗来实现这个功能。
首先需要从xml文件中加载参数,并将它们存储到如下变量中:
int nameStart;
int nameLenght;
int placeStart;
int placeLenght;
.....
读取文件后:
List<InputFileConvertor> inputList = new ......
string[] lines =System.IO.File.ReadAllLines(@"C:'Data.txt");
foreach(String line in lines)
{
InputFileConvertor lineInput = new InputFileConvertor();
lineInput.Name = line.Substring(nameStart,nameLenght);
//maybe remove the white spaces with String.Trim() or Regex.Replace(text,@"s","");
//fill also the other properties
inputList.Add(lineInput);
}