Click here to Skip to main content
15,867,704 members
Articles / Web Development / HTML

How to Create Xml Poll

Rate me:
Please Sign up or sign in to vote.
4.24/5 (18 votes)
12 Feb 2011CPOL2 min read 54.2K   978   51   10
The subject of our new article is to develop a simple and a nice poll application.
poll results

Introduction

The subject of our new article is to develop a simple and nice poll application that we can use in our web-sites. Although most of the samples use the database to save the poll data, our choice will be XML.

Why XML?

In practice, internet users aren't so interested in applications such as polls. In this case, we can assume that lots of people cannot vote simultaneously. In such cases, using XML data structure will be a logical choice in order for performance and coding.

Poll Data

We are keeping all of the data about the poll in an XML file. As its structure, while the value offered to the user is being kept in the node attributes, the poll data collected will be kept in the nodes.

XML
<?xml version="1.0" encoding="iso-8859-9" ?>
<poll name="Which OS do you use?">
  <answer text="Windows?">60</answer>
  <answer text="Mac OS">15</answer>
  <answer text="Linux">8</answer>
  <answer text="BeOS">2</answer>
</poll>

soluiton.gif

Note: Keeping the data files under the App_Data will prevent the users from accessing it directly.

Poll Web User Control

In order to provide an easy usage within the site, we are designing the poll application as a web user control. Because the application has two different appearances, we are dividing our ascx file into two logical parts by providing benefits from MultiView control. The first one is the part that includes the poll questions and also it is the part where the user will vote and the other part will be the one where they will see the poll results.

ASP.NET
    <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
    <asp:View ID="View1" runat="server">
        <table>
            <tr>
                <td id="header">
                    POLL
                </td>
            </tr>
            <tr>
                <td id="head">
                    <asp:Label ID="lblHead" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:RadioButtonList ID="rbQ" runat="server" Width="95%">
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr>
                <td id="footer">
                    <asp:Button ID="btnSubmit" runat="server" 
                     OnClick="btnSubmit_Click" Text="Submit" />
                </td>
            </tr>
        </table>
    </asp:View>
    <asp:View ID="View2" runat="server">
        <asp:Xml ID="Xml1" runat="server" DocumentSource="~/App_Data/pollData.xml" 
         TransformSource="~/App_Data/pollView.xsl"></asp:Xml>
    </asp:View>
</asp:MultiView>

Writing Code

When the web form is first loaded, by using LinqToXml, we are getting the data from the XML file.

C#
if (!IsPostBack)
{
	if (IsExist(GetIpAddress()))
                    MultiView1.ActiveViewIndex = 1;
	else
	{
		MultiView1.ActiveViewIndex = 0;
		pollInformation();
	}
}

void pollInformation()
{
	string path = Server.MapPath(@"App_Data/pollData.xml");
	//input xml doc
	XDocument myXml = XDocument.Load(path);
	//get header
	lblHead.Text = myXml.Element("Poll").Attribute("name").Value;
	//get answers
	foreach (var att in myXml.Element("Poll").Elements("answer"))
	rbQ.Items.Add(att.Attribute("text").Value);
}

After loading the file into the memory with the XDocument, one by one;

  • we are setting the poll header to the Text property of the Label control
  • we are adding the questions (items count) to the RadioButtonList as an Item
C#
protected void btnSubmit_Click(object sender, EventArgs e)
{
	string IpAddress = GetIpAddress();
	if (rbQ.SelectedValue != string.Empty && !IsExist(IpAddress))
	{
		string path = Server.MapPath(@"App_Data/pollData.xml");
		//input xml doc
		XDocument myXml = XDocument.Load(path);
		//get value of vote
		int value = Convert.ToInt32(myXml
                    .Descendants("answer")
                    .Where(n => ((string)n.Attribute("text").Value == 
				rbQ.SelectedValue)).Single().Value);
		//increase value +1
		value++;
		//set new value of vote
		myXml.Descendants("answer").Single(n => ((string)n.Attribute
		("text").Value == rbQ.SelectedValue)).Value = value.ToString();
		//save xml doc
		myXml.Save(path);
		//add ipaddress
		AddIpAddress(IpAddress);
	}
	MultiView1.ActiveViewIndex = 1;
}

In the voting part of poll whose presentation is completed, we are increasing the value of the node which belongs to the selected question to 1. In order to do this, we are querying the value of the selected item from radiobuttonlist control according to the belonging property and we'll get the concerned value. And then, we are saving the XML data again.

Poll Results with XSLT

And now, it is time for viewing the poll results. We are showing the data which is based on the idea that if there is an XML, there is also XSLT.

XML
 <?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <xsl:variable name="summ" select="sum(Poll/answer)"></xsl:variable>
    <table>
      <tr>
        <td id="header" colspan="3">POLL RESULTS</td>
      </tr>
      <tr>
        <td id="head" colspan="3">
          <xsl:value-of select="Poll/@name"/>
        </td>
      </tr>
      <xsl:for-each select="Poll/answer">
        <tr>
          <td width="120">
            <xsl:value-of select="@text"/>
          </td>
          <td id="value">
            %<xsl:value-of select="format-number(. * 100 div $summ,'0')"/>
          </td>
          <td width="100">
            <xsl:variable name="innerSumm" select=". * 100 div $summ"></xsl:variable>
            <img src="images/bar.png" height="10" width="{$innerSumm}%" />
          </td>
        </tr>
      </xsl:for-each>
    </table>
  </xsl:template>
</xsl:stylesheet>

There is no doubt that the most important part in here is calculating the percentage of the votes...

XML
%<xsl:value-of select="format-number(. * 100 div $summ,'0')"/>

...and determining the bar of poll picture according to the percentage.

<img src="images/bar.png" height="10" width="{$innerSumm}%" />

Result

We have seen that the couple XML and XSLT produce lots of practical results one more time. Our aim is not to write too much code, but to use the technology efficiently and in place.

Update

  • Preventing multiple votes

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer speak
Turkey Turkey
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralPreventing Multiple Votes PinPopular
primrotal13-May-08 4:04
primrotal13-May-08 4:04 
AnswerRe: Preventing Multiple Votes Pin
ayrilmaz13-May-08 4:17
ayrilmaz13-May-08 4:17 

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.