我有一个xml文件,如下所示。在其中,我想选择节点中的值并将其插入其单独的字典中。我下面有我的代码。当我遍历时,字典计数返回零。请提出建议。
<EmployeeFinance>
<EstateId>157</EstateId>
<EmpPersonal_Id>494</EmpPersonal_Id>
<NonStatDedct>
<DeductedAmt NonStatID="106">5000</DeductedAmt>
<DeductedAmt DeductionID="106">5000</DeductedAmt>
</NonStatDedct>
</EmployeeFinance>
。
var query = from nm in xelement.Descendants("EmployeeFinance")
where (int)nm.Element("EmpPersonal_Id") == empID
select new NonStatDed_Breakdown
{
Nonst = nm.Element("NonStatDedct").Elements("DeductedAmt").Where(a => a.Attributes().Equals("NonStatID")).ToDictionary(a => (int)a.Attribute("NonStatID"), a => (double)a),
Deduc = nm.Element("NonStatDedct").Elements("DeductedAmt").Where(a => a.Attributes().Equals("DeductionID")).ToDictionary(a => (int)a.Attribute("DeductionID"), a => (double)a)
};
var resultquery = query.SingleOrDefault();
当我检查resultquery.Nonst
和时resultquery.Deduc
,计数返回0。我不知道我在做什么错。
这行没有意义:
a.Attributes().Equals("NonStatID")
您需要获取属性值,并将其与实际值而不是属性名称进行比较:
.Where(a => (int)a.Attribute("NonStatID") == statId)
或者,如果您正在寻找属性名称,则可以使用如下Any
方法Where
:
.First(a => a.Attributes().Any(x => x.Name == "NonStatID"))
因此,您的代码应如下所示:
var query = from nm in xelement.Descendants("EmployeeFinance")
where (int)nm.Element("EmpPersonal_Id") == empID
select new NonStatDed_Breakdown
{
Nonst = nm.Element("NonStatDedct")
.Elements("DeductedAmt")
.Where(a => a.Attributes().Any(x => x.Name == "NonStatID"))
.ToDictionary(a => (int)a.Attribute("NonStatID"), a => (double)a),
Deduc = nm.Element("NonStatDedct")
.Elements("DeductedAmt")
.Where(a => a.Attributes().Any(x => x.Name == "DeductionID"))
.ToDictionary(a => (int)a.Attribute("DeductionID"), a => (double)a)
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句