1
我正在從第三方XML文件中讀取數據(因此我無法控制這些文件的結構和內容)。不一致的XML文件結構
在某些情況下,文件沒有一致的元素/屬性,所以當我嘗試準備通過該文件的程序崩潰。
反正是有檢查,如果每個存在的屬性通過,跳過屬性或默認爲空值,而不跳過整個記錄即我仍然希望其餘字段。
註釋掉的屬性當前並不總是出現在每個記錄中,即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;
}