【问题标题】:How I can bind a XDocument obect to DropDownList?如何将 Document 对象绑定到 DropDownList?
【发布时间】:2013-10-21 16:31:37
【问题描述】:

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

我的 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"。我该怎么做呢

【问题讨论】:

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


    【解决方案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;
    

    【讨论】:

      【解决方案2】:
      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 会是更好的解决方案 *

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-24
        • 2021-10-16
        • 2011-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多