如何将 XDocument obect 绑定到 DropDownList
本文关键字:绑定 DropDownList obect XDocument | 更新日期: 2023-09-27 18:35:09
hi 我想在 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"。我该怎么做
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,这将是更好的解决方案*
您可以从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;