Learning LINQ to XML
Since releasing the first version of GetHuman app for Windows Phone it has been a while since I have been working on any new apps. I decided to finish up a small app that I had started some time back, namely the APFT (Army Physical Fitness Test) Calculator app. To begin with this app I began to attempt deriving formulas to compute the scores, but soon realized two things:
- One: Deriving all the formulas to compute the scores for each event in the APFT would take me longer than writing a quick look up function, and…
- Two: I had never used LINQ to XML before and this was an excuse to learn how to use this.
To begin I took the APFT score charts and converted them into XML files based on their event and gender. Then I simply created a method that when invoked it takes the amount of repetitions the person scored in the event and returns the points for that level of reps for their age bracket. For the run I did a similar look up, but since you are going for a lower time rather than higher number of reps, I changed my comparison to >= in the where clause. The final code (in C# that is) you end up with looks a little something like this:
XDocument scoreXML = XDocument.Load("Data/malePushup.xml"); var query = from c in scoreXML.Descendants("score") where (int)c.Element("rep") <= eventReps select (int)c.Element("age" + pickAge.SelectedIndex); return query.Max();
This simple little LINQ command searches my XML file malePushup.xml for the all elements that have an element of “rep” that is less than or equal to the int “eventReps”, which in this case is how many repetitions the person performed on this event. Then it grabs all the values of the element for their respective age bracket (i.e. the first age bracket would be age0 since the SelectedIndex would be 0). Lastly it returns the highest score in this set of elements, which is the score the person received on this event.
For reference, here is the XML structure I was using in this example:
<malePushup> <score> <rep>0</rep> <age0>0</age0> </score> <score> <rep>5</rep> <age0>9</age0> </score> </malePushup>
Here is the full XML file I used for the example above: malePushup.xml
After finishing this part of the app, I am now working on adding a logging system and creating the scoring page to display bars of where your score falls on the 100 point scale. I also realized early on that I could have accomplished this same task using JSON instead of XML resulting in slightly smaller files, but since the XML files come with the app install and don’t need to be pulled from the web there didn’t seem to be any reason to worry about the small (~10-15KB) size difference. Also this was more of a learning experience with XML and LINQ since I had already worked with JSON a little bit in the GetHuman app.