Click here to Skip to main content
13,410,032 members (38,054 online)
Click here to Skip to main content
Add your own
alternative version


193 bookmarked
Posted 20 Aug 2002

Online Quiz

, 27 Aug 2002
Rate this:
Please Sign up or sign in to vote.
Create a multiple-choice quiz using XML DOM and XPath
<!-- Download Links --> <!-- Article image -->

Sample Image - xmlquiz_snapshot.gif

<!-- Add the rest of your HTML here -->


The idea to write an online quiz came up when I was looking for an XML tutorial. I visited and found not only the tutorial I was looking for, but more interestingly was an online quiz. I took the 20-questions quiz once, and hey! I felt great about it. I wonder why there are just few web sites offering online quiz like that.

A quiz is a great way to test your knowledge. An online quiz is a great addition to your web site that could keep your visitors glued for a few more minutes.

Download the demo project and try it. It is a 10-question quiz to challenge your knowledge about Australian geography. Don't worry! All data is kept in a clear, human-readable XML document, so you could easily peek for answers.

The Script Explained

I will not go through a very detail discussion about the script, but rather highlight several areas in the script. Once you get the whole idea about the script, then it is easy to modify or extend the script to suit your requirements.

Recursive Script

There is only one aspx script to do various tasks in the online quiz. It is a recursive script: a script that 'calls' itself over and over again until a certain condition is reached. Precisely, the script does not call itself, but posts form data to itself. This process is known as post back.

As the script posts back to itself continuously over the duration of the quiz, we could say that it has many states. The first state is to initialize several essential variables, count the total question, and record the quiz start time. Then, in the first and each following state, the script displays a multiple choice question to challenge user (see the snapshot above). A user answering the question will trigger onClick event, forcing a post-back, and move the script to the next state. In the next state, the script will run a subroutine associated with the event to check the answer and display the next multiple question. The recursive flow repeats again and again, until the last question is processed, where at this point a result is displayed.

The following activity diagram represents the recursive flow of the online quiz script. 

Maintaining State

The online quiz script needs to maintain state of its variables. There are a bunch of alternatives to do so. The most advanced way is to use the session object, and the conventional way is to use hidden inputs or a QueryString. ASP.NET introduces another alternative called 'state bag'. Unlike the session object, state bag is not persisted over the whole user session, but is brought forward from one page to another page just like hidden inputs and querystring. However, it is superior to hidden inputs and QueryStrings, since it can accept more data types and the content has been encoded into a single string and therefore is not easy to tamper with.

Storing value into state bag:

ViewState("TotalQuestion") = intTotalQuestion

Getting value from state bag:

intTotalQuestion = ViewState("TotalQuestion")

The following is a list of variables to be kept in the state bag:

Variable Name State Bag Name Data Type Comments
intTotalQuestion TotalQuestion int Keeps the total question in the quiz. The value is populated in the first state of the quiz and remains constants over the duration of quiz.
intScore Score int Keeps the number of correct answer.
intQuestionNo QuestionNo int Holds the last question number the user attempted.
arrAnswerHistory AnswerHistory arraylist of int Records answers in the quiz. It will record 0 (zero) if the answer is correct, otherwise record the selectedindex of the radio buttons.
(none) CorrectAnswer int Holds the correct answer of previous question. It is made available in the next state when the answer is checked for correctness.
(none) StartTime date Holds the start time of the quiz. It is used to calculate the time spent in the quiz.


XML Data

Data for the online quiz is kept in an XML document named quiz.xml, which is validated using an XML schema named quiz.xsd. A valid XML document consists of a root element called quiz, which has at least one element called mchoice (short for multiple-choice). Each mchoice element has one question child element, and two or more answer child elements. The answer element may have the correct attribute with possible value of either yes or no. In fact, you should supply the correct attribute with a value of yes to one of the answers in the same mchoice, otherwise there will be no correct answer for the question.


<?xml version="1.0" encoding="UTF-8"?>
<quiz xmlns:xsi=""

    <question>What is the capital city of Australia ?</question>
    <answer correct="yes">Canberra</answer>
    <answer>Gold Coast</answer>
    <question>Which city has an extensive tram network?</question>
    <answer correct="yes">Melbourne</answer>

It is possible to insert HTML tags within the XML data, therefore the quiz may contain decorated texts, images, links, etc. instead of plain text. Just make sure to enclose the HTML tags with CDATA block, so the XML document is still valid. Look at the following example:

    <question><![CDATA[<span class="code-SummaryComment">Which of the following is <u>NOT</u> 
Australian native animals?]]></span></question>
    <answer correct="yes">Penguin</answer>


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs=""

elementFormDefault="qualified" attributeFormDefault="unqualified">
  <xs:element name="quiz">
        <xs:element name="mchoice" maxOccurs="unbounded">
              <xs:element name="question" type="xs:string"/>
              <xs:element name="answer" minOccurs="2" maxOccurs="unbounded">
                    <xs:extension base="xs:string">
                      <xs:attribute name="correct" use="optional">
                          <xs:restriction base="xs:string">
                            <xs:enumeration value="yes"/>
                            <xs:enumeration value="no"/>

The online quiz script does not validate the XML document against the XML Schema for several reasons. First, it is a resource intensive process, forcing

to go through each element and attribute in the XML document. Second, we need to validate the XML document just once after it has been updated, instead of every time we load the file. To validate the XML document, you could write a separate aspx script or use a third-party tool and run them manually every after you finish updating the XML document.

XML Document Object Model

XML Document Object Model (DOM) is a tree-like structure that represents every node of an XML document based on the hierarchical relationship with its parent nodes and child nodes. The DOM allows us to navigate and manipulate XML document in more logical way.

To build an XML DOM, we use the XMLDocument class. The XMLDocument class itself extends the XMLNode class, therefore many of its properties and methods are inherited from XMLNode. While XMLNode's methods and properties apply to a specific node in an XML document, methods and properties of XMLDocument apply to the whole XML document.

The following code create an instance of XMLDocument and build XML DOM from quiz.xml:

Dim xDoc as XMLDocument = New XMLDocument()

Addressing a specific node in the XML DOM is a bit tricky. We should navigate our 'pointer' through the DOM starting from its root node. The following code demonstrates how to address the first question of the first multiple choice:

Dim xNode as XMLNode

'Goto the first/base element in the file, which is <?xml ?>
xNode = xDoc.DocumentElement

'Goto the next sibling of current node, which is <quiz>
xNode = xNode.NextSibling

'Goto the first child of current node, which is <mchoice>
xNode = xNode.FirstChild

'Goto the first child of current node, which is <quiz>
xNode = xNode.FirstChild

'Print the content of current node
Response.Write("The question is: " & xNode.InnerHtml)

It is definitely a tedious task, particularly if you want to address nodes located at a very low level in the hierarchy. Luckily, we can utilize the XPath language to more directly address a specific node or a group of nodes. If you are unfamiliar with XPath, it will be briefly explained in the next section.

The SelectNodes method of the XMLNode and XMLDocument class' accepts an XPath string and returns a collection of XMLNode objects, called

. Another method, SelectSingleNode, does just the same thing but return only a single XMLNode object.

'Using SelectNodes to address all answers of the first multiple choice
Dim xNodeList As XMLNodeList
Dim i as Integer
xNodeList = xDoc.SelectNodes("/quiz/mchoice[1]/answer")
For i = 0 to xNodeList.Count-1
  Response.Write("<p>" & xNodeList.Item(i).InnerHtml)

'Using SelectSingleNode to select the first question of the first multiple choice
Dim xNode as XMLNode
xNode = xDoc.SelectSingleNode("/quiz/mchoice[1]/question")
Response.Write("The question is: " & xNode.InnerHtml)


XPath is a language to address specific nodes in an XML document. It could address a single node or a group of nodes by describing its hierarchy relationship in a string, therefore it is often called an XPath string. If you are familiar with file path or URL, then the concept of XPath is nothing new.

Read the XPath string from left to right and you will be able to figure out the node it is addressing. Except for several conditions and functions, XPath is actually easy to use. The following table demonstrates some usage of XPath against quiz.xml:

XPath String Result
/quiz Select the root node of XML including all elements it contains. 
/quiz/mchoice Select all mchoice child elements of the quiz
/quiz/mchoice[1] Select the first mchoice (multiple choice) child element of the quiz
/quiz/mchoice[1]/question Select all questions of the first multiple choice of the quiz
/quiz/mchoice[1]/answer[4] Select the fourth answer of the first multiple choice of the quiz
/quiz/mchoice[1]/answer[4]/@correct Select 'correct' attribute of the fourth answer of the first multiple choice of the quiz

XPath contains a lot more surprises. If you are interested enough to explore more, check out the XPath Tutorial at W3CSchools.


This article presented an online quiz as a tool to add interactivity to your web site. It also explored several topics like recursive scripts, navigating and manipulating XML documents using the XML DOM, a glimpse of the XPath language, and a brief discussion about state maintenance.



This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Enrico Elizar Samuel
Web Developer
Singapore Singapore
Currently, he is in Singapore doing a contract work for a multinational company. During weekend, he is busy exploring Singapore with his lovely fiance to find the best food.

You may also be interested in...

Comments and Discussions

GeneralMessage Closed Pin
24-Jan-18 2:19
memberMember 1364088924-Jan-18 2:19 
QuestionMessage Closed Pin
7-Apr-17 10:39
memberKaren kumar7-Apr-17 10:39 
QuestionOnline Quiz Application Using JSP Servlet Pin
MAHTAB__ALAM12-Jan-15 2:51
memberMAHTAB__ALAM12-Jan-15 2:51 
AnswerMessage Closed Pin
13-Jan-15 23:52
memberMohammad Tuaha13-Jan-15 23:52 
GeneralMy vote of 5 Pin
Member 1025467022-Apr-14 2:18
memberMember 1025467022-Apr-14 2:18 
QuestionThank you Pin
sabaaqeel5-Feb-14 3:44
membersabaaqeel5-Feb-14 3:44 
QuestionXSL for images or CDATA? Pin
paulhennessy19863-Jan-13 17:31
memberpaulhennessy19863-Jan-13 17:31 
Questiongreat article Pin
muhamd yusuf21-Dec-11 2:02
membermuhamd yusuf21-Dec-11 2:02 
GeneralMy vote of 5 Pin
amitkarnik221128-Nov-11 19:54
memberamitkarnik221128-Nov-11 19:54 
QuestionGreat article Pin
john30s30-Aug-11 9:27
memberjohn30s30-Aug-11 9:27 
QuestionPlease can you tell me why you are using the quiz.xsd ? Pin
mhamad zarif23-Aug-11 8:32
membermhamad zarif23-Aug-11 8:32 
GeneralNeed help in rewrite the VB to C# Pin
boonjye9-May-11 5:17
memberboonjye9-May-11 5:17 
GeneralThank You for great idea Pin
JyotiDudeja22-May-11 8:49
memberJyotiDudeja22-May-11 8:49 
QuestionHow to run this code Pin
Prasnna665-Sep-10 22:27
memberPrasnna665-Sep-10 22:27 
GeneralGood articles Pin
vermaanil198512-Aug-10 20:34
membervermaanil198512-Aug-10 20:34 
GeneralMy vote of 1 Pin
PadminiGiri27-Jan-10 22:44
memberPadminiGiri27-Jan-10 22:44 
GeneralRe: My vote of 1 Pin
SAKryukov6-Jan-11 16:18
memberSAKryukov6-Jan-11 16:18 
Generalim unable to run this code Pin
shahmurtaza3-Sep-09 2:02
membershahmurtaza3-Sep-09 2:02 
GeneralRe: im unable to run this code Pin
DevIndia25-Jul-10 22:17
memberDevIndia25-Jul-10 22:17 
GeneralRe: im unable to run this code Pin
sandeepkrohan15-Jul-11 10:02
membersandeepkrohan15-Jul-11 10:02 
GeneralViewstate Problem in C# Pin
fvdfnksdfjk26-May-09 21:42
memberfvdfnksdfjk26-May-09 21:42 
GeneralRe: Viewstate Problem in C# Pin
sreckoo11-Feb-10 0:19
membersreckoo11-Feb-10 0:19 
GeneralRe: Viewstate Problem in C# Pin
boonjye9-May-11 5:19
memberboonjye9-May-11 5:19 
GeneralImage in each one choice and label [modified] Pin
dafepi200415-Mar-09 17:54
memberdafepi200415-Mar-09 17:54 
QuestionTool not working in MAC Pin
eashwar1122-Oct-08 11:44
membereashwar1122-Oct-08 11:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.180221.1 | Last Updated 28 Aug 2002
Article Copyright 2002 by Enrico Elizar Samuel
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid