A reader sent me an email asking how to write a program that would "manage option based exams". He wanted a system that would ...
- Classify questions according to topic, skills and objectives
- Make a random question selection
(Well ... Actually, he wanted it to do even more. But I have coded the hard parts.)
As I thought about the best way to solve the problem, I decided that this would be an ideal example to showcase the way to use one of Microsoft's most amazing new technologies, LINQ to XML. I've written several articles about LINQ, but I decided a complete system might work better in showing how to use it. Code snippets often fail because it's not clear how they actually fit in to a whole system.
Besides ... Writing it seemed like it would be a lot of fun.
You can download the entire source for the program, including the XML files, at the end of the article.
LINQ is can be confusing mainly due to the syntax, not the concepts. Most people 'get' the idea of loading an XML document immediately. It's like loading a file, right? Ummmm ... Not quite.
First, you can load XML in a variety of different ways, from using XMLReader to the Load method. Second, you can load the XML into different kinds of XML objects, such as an XDocument or an XElement.
All these bewildering choices (and they're not limited to just loading XML) are available in part because Microsoft has been learning a lot about XML in the few years since it burst onto the scene. The earliest implementations using technologies like XPath were pretty difficult. LINQ is a lot easier and more intuitive, but Microsoft is maintaining "backward compatibility" in .NET and so all of the harder choices are still there. Worse, you can mix and match syntax in many of the statements. So there are sometimes several ways to write the same statement that work. Finally, following the successful model of HTML, a lot of the incorrect ways to code the syntax don't make the program crash - they just don't give you the right answer. (They usually don't give you any answer. They just return an empty object.) This is great for crash free programs but terrible for debugging so the program does what you want.
More that most technologies, exhaustive testing is recommended for LINQ and XML. Just because it runs, never assume it's right.
On the next page, the actual coding begins!


