【问题标题】:Selecting from xml file into a dictionary从 xml 文件中选择到字典中
【发布时间】:2014-03-14 15:50:23
【问题描述】:

我有一个如下所示的 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.Nonstresultquery.Deduc 时,计数返回0。我不知道我做错了什么。

【问题讨论】:

    标签: c# xml dictionary linq-to-xml


    【解决方案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)
        };
    

    【讨论】:

    • 我没有像 StatId 这样的真实值。这就是为什么我试图查询属性名称是“NonStatID”的原因。我可以这样做吗?
    • 在部分 - .ToDictionary(a => (int)a.Attribute("NonStatID"), a => (double)a) .. 我收到一个错误,说 .ToDictionary 定义是不在那里..
    • @Maverick1415 是我的错。先改到 Where
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多