我有这个 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/