The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

skea (2) [Avatar] Offline
#1
Somebody help me. I cant figure out this. I would like to get the percentage of votes by each candidate in every province. Something like .

Percentage for Sam_Kea=

(Total_Sum_Of_Votes_Cast_for_Sam_Kea_In_All_Pronvinces / Total_Sum_Of_Votes_Cast_For_All_Candidates_In_All_Pronvinces)* 100.

Here is my xml below.

1 <root>
2 <Candidates>
3 <Sam_Kea/>
4 <Jeje/>
5 <John_Doe/>
6 </Candidates>
7
8 <Provinces>
9 <Province name='ProvinceA' Registered_Voters='115852'>
10 <Candidate name='Sam_Kea' votes='100'/>
11 <Candidate name='Jeje' votes='500'/>
12 <Candidate name='John_Doe' votes='400'/>
13 </Province>
14
15 <Province name='ProvinceB' Registered_Voters='25852'>
16 <Candidate name='Sam_Kea' votes='200'/>
17 <Candidate name='Jeje' votes='100'/>
18 <Candidate name='John_Doe' votes='300'/>
19 </Province>
20
21 <Province name='ProvinceC' Registered_Voters='317684'>
22 <Candidate name='Sam_Kea' votes='1000'/>
23 <Candidate name='Jeje' votes='1200'/>
24 <Candidate name='John_Doe' votes='190'/>
25 </Province>
26 </Provinces>
27
28 </root>
29
fabrice.marguerie (224) [Avatar] Offline
#2
Re: Get Percentage linq2xml
What about this very direct solution?:

[pre]var xml = XElement.Parse(yourXmlString);
var votesForCandidate =
xml
.Descendants("Candidate")
.Where(c => (String)c.Attribute("name"smilie == "Sam_Kea"smilie
.Sum(c => (int)c.Attribute("votes"smilie);
var totalVotes =
xml
.Descendants("Candidate")
.Sum(c => (int)c.Attribute("votes"smilie);
var result = (double)votesForCandidate / totalVotes * 100;
[/pre]
Fabrice
skea (2) [Avatar] Offline
#3
Re: Get Percentage linq2xml
Thanks so much.This has helped me alot.
I wish i had not restructured mu xml file. processing attributes is such a pain.