2012-01-09 123 views
2

我有以下XML文檔:從XML填充下拉列表使用LINQ

<?xml version="1.0" encoding="utf-8" ?> 
<dropdowns> 

    <dropdown name="DropDownLoc"> 
    <menu text="Select" value="-1" /> 
    <menu text="North" value="1200" /> 
    <menu text="South" value="1400" /> 
    </dropdown> 

    <dropdown nome="DropDownEsp"> 
    <menu text="Select" value="-1" /> 
    <menu text="Est" value="7" /> 
    <menu text="Ovest" value="9" /> 
    </dropdown> 
</dropdowns> 

我想讀這個XML和填充兩個下拉列表中給定的下拉列表名稱(如「DropDownEsp」)的方法 我想爲了完成這與linq,誰可以幫助我嗎?

+1

你到目前爲止嘗試過什麼?哪些問題遇到了LINQ-to-xml或動態下拉對象? – sll 2012-01-09 20:02:23

回答

1

下面的代碼,這將有助於您讀取XML和創建項目(ListItem)的列表:

// or use XDocument.Parse("xml string") to parse string 
XDocument xdoc = XDocument.Load(@"c:\testxml.xml"); 
var dropLists = xdoc.Descendants("dropdown") 
       .Select(d => d.Descendants("menu").Select(m => 
         new /* new ListItem(text, value) */ 
         { 
          Text = m.Attribute("text"), 
          Value = m.Attribute("value") 
         })) 
       .ToList(); 

嘗試添加項目到控制自己。

1

如果你有你的.aspx頁面的空白<asp:DropDownList ID="DynamicDropDown" runat="server" />控制,可以將數據綁定它LINQ查詢的結果是這樣的:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!Page.IsPostBack) 
    { 
    // Assuming your XML file is in the App_Data folder in the root of your website 
    string path = Server.MapPath("~/App_Data/DropDowns.xml"); 

    // Let's say we want to use the options from the second <dropdown>-tag in your XML 
    string whichDropDown = "DropDownEsp"; 

    // This is the LINQ query to find those options from the XML 
    // and turn them into ListItem objects 
    var query = 
     from dropDown in XDocument.Load(path).Descendants("dropdown") 
     where dropDown.Attribute("name").Value == whichDropDown 

     from name in dropDown.Descendants("name") 
     let text = name.Attribute("text").value 
     let value = name.Attribute("value").value 

     select new ListItem(text, value); 

    // Now we data bind the query result to the control 
    DynamicDropDown.DataSource = query; 
    DynamicDropDown.DataBind(); 
    } 
} 

在LINQ查詢我們首先選擇只有<dropdown>元素用正確的名稱(基於whichDropDown變量)。然後我們選擇所有<name>元素,並從每個元素中我們將屬性值放入textvalue值中。然後我們使用這些值創建一個新的ListItem(爲每個<name>元素創建一個)。

然後可以使用此結果來綁定數據綁定控件。