c# - 使用 XML 文件绑定(bind)下拉列表

标签 c# .net asp.net xml

我有这个 XML 文件:

<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>

如何将每个问题绑定(bind)到 C# 中的特定下拉列表?

谢谢

最佳答案

你可以使用 XmlDataSource .因为您的 XML 不符合此控件的预期,您需要使用 XSL 转换来调整它。

所以第 1 步:

定义一个 XSL 转换(~/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>

第 2 步:

使用它:

<%@ 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>

注意数据源上的 TransformFile 属性如何指向 XSL 文件。

关于c# - 使用 XML 文件绑定(bind)下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4316787/

相关文章:

c# - 使用 Azure 图形 API 获取用户下的用户列表

.net - 向客户报告模型状态和应用程序错误的推荐方法是什么?

.net - 有什么原因导致 VB6 无法移植到 .Net 上吗?

asp.net - 加速 ASP.NET 开发

带套接字 tcp 的 C# ssl/tls

c# - 我应该使用 System.Net.Http Nuget 包吗?

c# - 在 C# 中使用 excel 中的模板

.net - System.IO.Compression.DeflateStream 的数据格式

c# - 以编程方式将数据插入word文件并保存在asp.net中

c# - 当 RegisterEventBus "No service for type Autofac.ILifetimeScope' 已注册时。