【发布时间】:2014-03-30 22:32:11
【问题描述】:
我正在从第 3 方 xml 文件中读取数据(因此我无法控制这些文件的结构和内容)。
在某些情况下,文件没有一致的元素/属性,因此当我尝试通过文件进行准备时,程序会崩溃。
是否无论如何都要检查每次传递时是否存在该属性并跳过该属性或将值默认为 null,而不跳过整个记录,即我仍然想要其余的字段。
注释掉的属性是当前并不总是出现在每条记录中的属性,即 AbbreviationChar 将出现在 xml 文件的前 30 条记录中,但第 31 条记录不会将此列为属性,然后在第 32 条记录中显示再次。
public IEnumerable<KronosPayCode> ImportPayCodes()
{
var processingOrder = _db.KronosConfigurationFiles.ToList();
if (!processingOrder.Any()) return null;
var xmlFile = Path.Combine(_xmlPath, "WSAPayCode.xml");
var stream = new FileStream(xmlFile, FileMode.Open, FileAccess.Read);
var xdoc = XDocument.Load(stream);
var payCodeCollection = xdoc.Descendants("WSAPayCode");
var kronosCollection = new List<KronosPayCode>();
foreach (var element in payCodeCollection)
{
var abbreviationChar = element.Attribute("AbbreviationChar");
var payCode = new KronosPayCode
{
Name = element.Attribute("Name").Value,
AutoResolved = element.Attribute("AutoResolved").Value.IsBool(),
EditExcuseAbsn = element.Attribute("EditExcuseAbsn").Value.IsBool(),
PersistPceSw = element.Attribute("PersistPceSw").Value.IsBool(),
//AbbreviationChar=element.Attribute("AbbreviationChar").Value,
EditCntToCdotSw=element.Attribute("EditCntToCdotSw").Value.IsBool(),
EditAffShfTotal=element.Attribute("EditAffShfTotal").Value.IsBool(),
EditCntToOt=element.Attribute("EditCntToOt").Value.IsBool(),
PayUsingWeightedAverageRate=element.Attribute("PayUsingWeightedAverageRate").Value.IsBool(),
RequiresMgrApproval=element.Attribute("RequiresMgrApproval").Value.IsBool(),
WeightedAverageRateIsComputedDaily=element.Attribute("WeightedAverageRateIsComputedDaily").Value.IsBool(),
JustAutoResExpAsWorked=element.Attribute("JustAutoResExpAsWorked").Value.IsBool(),
AssociatedDurationPayCodeName=element.Attribute("AssociatedDurationPayCodeName").Value,
WeightedAverageRateContributionsUseAnAdjustedRate=element.Attribute("WeightedAverageRateContributionsUseAnAdjustedRate").Value.IsBool(),
ScheduleHoursType=element.Attribute("ScheduleHoursType").Value,
CheckAvlbltySw=element.Attribute("CheckAvlbltySw").Value.IsBool(),
//WageAddition=element.Attribute("WageAddition").Value,
VisibleInMainArea=element.Attribute("VisibleInMainArea").Value.IsBool(),
IsMoneyCategory=element.Attribute("IsMoneyCategory").Value.IsBool(),
AmountType=element.Attribute("AmountType").Value,
VisibleInReport=element.Attribute("VisibleInReport").Value.IsBool(),
ContributesToWeightedAverageRates=element.Attribute("ContributesToWeightedAverageRates").Value.IsBool(),
//UnjustAutoResExpAsWorked=element.Attribute("UnjustAutoResExpAsWorked").Value.IsBool(),
//WageMultiply=element.Attribute("WageMultiply").Value,
//Type=element.Attribute("Type").Value,
//VisibleToUser=element.Attribute("VisibleToUser").Value.IsBool(),
CustomerId = 11,
};
_db.KronosPayCodes.Add(payCode);
_db.SaveChanges();
kronosCollection.Add(payCode);
}
return kronosCollection;
}
【问题讨论】: