简体   繁体   中英

Selecting from xml file into a dictionary

I have an xml file as shown below. In it i want to select the values in the nodes and insert them into their separate dictionary. I have my code below. When i iterate through, the dictionary count returns zero. Suggestions please.

 <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();

When i check resultquery.Nonst and resultquery.Deduc , the count returns 0. I do not know what i am doing wrong.

This line doesn't make sense:

a.Attributes().Equals("NonStatID")

You need to get your attribute value and compare it with a real value not the name of the attribute:

.Where(a => (int)a.Attribute("NonStatID") ==  statId)

Or if you are looking for attribute name then you can use Any method with Where like this:

.First(a => a.Attributes().Any(x => x.Name == "NonStatID"))

So then your code should look like this:

 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)
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM