从XmlDataSource填充DropDownList [英] Populate DropDownList from XmlDataSource

查看:115
本文介绍了从XmlDataSource填充DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个简单的xml文件填充我的DropDownList:

I'd like to populate my DropDownList using a simple xml file:

<?xml version="1.0" encoding="utf-8" ?>
<Databases>
  <Database>foo</Database>
  <Database>bar</Database>
  <Database>baz</Database>
</Databases>

我的XPath是

/Databases/Database

我的下拉列表呈现为:

<select name="databaseDropDownList" id="databaseDropDownList"> 
                    <option selected="selected" value="System.Web.UI.WebControls.XmlDataSourceNodeDescriptor">System.Web.UI.WebControls.XmlDataSourceNodeDescriptor</option>
                    <option value="System.Web.UI.WebControls.XmlDataSourceNodeDescriptor">System.Web.UI.WebControls.XmlDataSourceNodeDescriptor</option>
                    <option value="System.Web.UI.WebControls.XmlDataSourceNodeDescriptor">System.Web.UI.WebControls.XmlDataSourceNodeDescriptor</option>
</select>

如何提取文本?

谢谢

推荐答案

我不能从头顶回忆起来,但我认为XmlDataSource中有一个错误,您绑定到xml节点的值。它只适用于属性。如果我错了,请更正我。您需要对XML文件进行一些修改:

I can't recall it from the top of my head but I think there was a bug in XmlDataSource that prevents you to bind to values of xml nodes. It works with attributes only. Please correct me if I am wrong with this. There's a slight modification you need to make to your XML file:

<%@ Page Language="C#" %>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string xml =
@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Databases>
  <Database name=""foo"" />
  <Database name=""bar"" />
  <Database name=""baz"" />
</Databases>";
            databasesSource.Data = xml;
            databasesSource.DataBind();
        }
    }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="databases" runat="server" DataSourceID="databasesSource" DataValueField="name" DataTextField="name" />
        <asp:XmlDataSource ID="databasesSource" runat="server" XPath="/Databases/Database" />
    </div>
    </form>
</body>
</html>

请注意,我添加了名称属性,而不是使用节点直接。

Note that I added the name attribute instead of using the value of the node directly.

如果您无法修改原始XML文件的结构,则可以使用 TransformFile 属性,如此 post

If you can't modify the structure of your original XML file you can apply an XSLT transformation on it using the TransformFile property as described in this post.

这篇关于从XmlDataSource填充DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆