[英]Importing a multiline record with optional fields using filehelpers
我正在解析一個記錄格式如下的文件:
mr
Sean r.
Farrow
4 The Crescent
Eastleake
Loughborough
Leicestershire
LE12 6QH
01509 59213
07525945447
sean.farrow@seanfarrow.co.uk
每條記錄都由一個空白行定界。 這兩個電話號碼和電子郵件地址是可選的。
解析此類記錄的最佳方法是什么? 我可以編寫自己的解析器,但我希望不必這樣做!
FileHelpers希望每條記錄以新行結尾,因此您必須在將輸入傳遞給引擎之前預先解析輸入。 這樣做很簡單-類似於:
var lines = File.ReadAllLines(pathToImportFile);
var sb = new StringBuilder();
var separator = ","; // use a comma as field delimiter
foreach (string line in lines)
{
if (String.IsNullOrEmpty(line))
sb.AppendLine(""); // convert empty lines into line feeds
else
sb.AppendFormat("\"{0}\"{1}", line, separator); // put quotes around the field to avoid problems with nested separators
}
var engine = new FileHelperEngine<MyClass>();
engine.ReadString(sb.ToString());
你的班級看起來像
[DelimitedRecord(",")]
class MyClass
{
[FieldQuoted(QuoteMode.AlwaysQuoted)]
public string Title;
[FieldQuoted(QuoteMode.AlwaysQuoted)]
public string FullName;
[FieldQuoted(QuoteMode.AlwaysQuoted)]
public string Address1;
/// ... etc
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.