2013-10-14 93 views
0

您好我想將我的XDocument對象包含在ASP.NET的DropDownList中。如何將XDocument綁定到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」。我怎樣才能做到這一點

回答

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

你可以從爲XMLDocument獲取的數據集,並設置下拉這樣

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; 
相關問題