如何将Document对象绑定到DropDownList?

时间:2013-10-14 06:34:49

标签: c# asp.net xml linq-to-xml

您好我想将我的XDocument对象包含在ASP.NET的DropDownList中。

我的ASPX:

<asp:DropDownList ID="drpLogLocation" runat="server" AutoPostBack=true onselectedindexchanged="drpLogLocation_SelectedIndexChanged">

我的C#代码:

XDocument x = XDocument.Load(Server.MapPath(@"~\App_Data\location.xml"));



                   x.Root.Descendants()
                                     .Where(e => !ActiveUserList.Contains((string)e.Attribute("group")))
                                     .ToList()
                                     .ForEach(s => s.Remove());


                   drpLogLocation.DataSource = x;// ?????????????
                   drpLogLocation.DataBind();

这是我的XML结构:

<plants>
  <plant id="DB" display="Dill" group="NPS_DB" />
  <plant id="SB" display="Süd" group="NPS_SB" />
</plants>

我想要DropDownList DataTextField =“display”和DataValueField =“id”。我该怎么做

2 个答案:

答案 0 :(得分:1)

XDocument xDoc = XDocument.Load(@"Yourxmlfile.xml");
        var query = from xEle in xDoc.Descendants("publication")
                    select new ListItem(xEle.Element("name").Value, xEle.Attribute("tcmid").Value);

        ddlList.DataValueField = "value";
        ddlList.DataTextField = "text";
        ddlList.DataSource = query;
        ddlList.DataBind();

* 使用Linq代替它将是更好的解决方案*

答案 1 :(得分:1)

您可以从XMLDocument获取DataSet并设置下拉列表

  string xml = @"<plants>  <plant id='DB' display='Dill' group='NPS_DB' />  <plant id='SB' display='Süd' group='NPS_SB' /></plants>";

        DataSet ds = new DataSet();
        ds.ReadXml(XmlReader.Create(new StringReader(xml)));
        ddlList.DataValueField = "DB";
        ddlList.DataTextField = "Dill";
        ddlList.DataSource = ds.Tables[0];
        ddlList.DataBind();

XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml(@"Yourxmlfile.xml");
DataSet ds = doc.DataSet;