Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind dropdown with XML file

Tags:

c#

.net

xml

asp.net

I have this XML file:

<questions>
  <question id="title">
    <option>
      <text>Mr</text>
      <value>Mr</value>
    </option>
    <option>
      <text>Ms</text>
      <value>Ms</value>
    </option>
  </question>
  <question id="organisation">
    <option>
      <text>org1</text>
      <value>org1</value>
    </option>
    <option>
      <text>org2</text>
      <value>org2</value>
    </option>
  </question>
</questions>

How do I bind each question to a specific drop-down in c#?

Thanks

like image 368
user Avatar asked Jun 16 '26 14:06

user


1 Answers

You could use a XmlDataSource. Because your XML is not conform to what this control expects you will need to adapt it by using a XSL transformation.

So Step 1:

Define a XSL transformation (~/App_Data/questions.xslt):

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="questions">
    <questions>
      <xsl:apply-templates select="question"/>
    </questions>
  </xsl:template>
  <xsl:template match="option">
    <option>
      <xsl:attribute name="text">
        <xsl:value-of select="text"/>
      </xsl:attribute>
      <xsl:attribute name="value">
        <xsl:value-of select="value"/>
      </xsl:attribute>
    </option>
  </xsl:template>
</xsl:stylesheet>

Step 2:

Use it:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="Form1" runat="server">
        <asp:DropDownList 
            ID="ddl" 
            runat="server" 
            DataSourceID="ds" 
            DataTextField="text" 
            DataValueField="value" 
        />

        <asp:XmlDataSource 
            ID="ds" 
            runat="server" 
            DataFile="~/App_Data/questions.xml" 
            TransformFile="~/App_Data/questions.xslt" 
            XPath="//option" 
        />
    </form>
</body>
</html>

Notice how the TransformFile property on the data source is pointing to the XSL file.

like image 77
Darin Dimitrov Avatar answered Jun 18 '26 05:06

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!