简体   繁体   English

如何在 Web.config 中设置 Xml 文件的路径并将 Xml 中的数据绑定到下拉列表中

[英]How to set the path of Xml file in Web.config and bind the data from Xml into drop down

I have a Xml file with values for the dropdown.I want to provide the path in Web.config and bind the values to drop down from web.config.我有一个 Xml 文件,其中包含下拉列表的值。我想在 Web.config 中提供路径并将值绑定到从 web.config 中下拉。

Firstly to read the location from web.config use System.Configuration class, something like the following should work首先从 web.config 使用 System.Configuration class 读取位置,类似下面的东西应该可以工作

string filePath = ConfigurationManager.AppSettings["FilePath"];

to access a file on the server use Server.MapPath eg访问服务器上的文件使用 Server.MapPath 例如

Server.MapPath(filepath);

to bind an xml file to the dropdown you could use the following, there are easier ways but this will allow for any other manipulation you need to do要将 xml 文件绑定到下拉列表,您可以使用以下方法,有更简单的方法,但这将允许您进行任何其他操作

1: Get the list of items 1:获取项目列表

public static List<string> GetFamiliesList()
    {
        List<string> families = new List<string>();
        try
        {
            using (StreamReader streamreader = new StreamReader(Server.MapPath(filepath)))
            {
                XElement xe = XElement.Load(streamreader);
                foreach (XElement children in xe.Elements("Family"))
                {
                    families.Add(children.Attribute("Name").Value);
                }
            }
        }
        catch
        {

        }
        return families;
    }

2: bind to dropdown 2:绑定到下拉菜单

 dropdownList.DataSource = GetFamiliesList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM