【发布时间】:2021-08-10 15:50:19
【问题描述】:
下面是示例xml文件代码
<?xml version="1.0" encoding="utf-8"?>
<Match>
<IDCIBILDOBMatch>100</IDCIBILDOBMatch>
</Match>
<VerificationScore>
<IDDOBScore>180</IDDOBScore>
<IDAltDOBScore>60</IDAltDOBScore>
</VerificationScore>
我想取Max值,非空值,这样如果所有值都为空,结果为空。
var dobMatchInformation = "";
var idALTDOBSCORE = "";
var idDOBScore = "";
XDocument document = XDocument.Parse(InputRequest);
bool Match_CIBILDOBMatch = document.Descendants("Match").Elements("IDCIBILDOBMatch").Any();
if (Match_CIBILDOBMatch == true)
{
dobMatchInformation = document.Descendants("Match").Elements("IDCIBILDOBMatch").FirstOrDefault().Value;
}
var dobscoreInformation = document.Descendants("VerificationScore");
bool Match_AltDOBScore = document.Descendants("VerificationScore").Elements("IDAltDOBScore").Any();
if (Match_AltDOBScore == true)
{
idALTDOBSCORE = dobscoreInformation.Select(x => x.Element("IDAltDOBScore").Value).Max();
}
bool Match_DOBScor = document.Descendants("VerificationScore").Elements("IDDOBScore").Any();
if (Match_DOBScor == true)
{
idDOBScore = dobscoreInformation.Select(x => x.Element("IDDOBScore").Value).Max();
}
var MAXDOBSCORE = Math.Max(Convert.ToInt32(dobMatchInformation), Math.Max(Convert.ToInt32(idALTDOBSCORE), Convert.ToInt32(idDOBScore)));
Math.Max 计算要处理空值。如果我当前的代码空值出现意味着出错
var MAXDOBSCORE = Math.Max(Convert.ToInt32(dobMatchInformation), Math.Max(Convert.ToInt32(idALTDOBSCORE), Convert.ToInt32(idDOBScore)));
【问题讨论】:
-
如果这些值是
null,那么问题出在Convert.Int32上,它将失败。添加null检查或切换到int.TryParse。当您成功解析一个值时,将其添加到List<int>,然后在其上调用Max,或者如果它为空,则使用nullint?。 -
我试过但没用。你能修改我的代码吗@juharr
标签: c# xml linq-to-xml