我有一个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.我不知道我做错了什么。
答案 0 :(得分:1)
这条线没有意义:
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)
};