簡體   English   中英

C#中的XML和IDictionary

[英]XML and IDictionary in C#

我的XML文件如下,

<state name ="Alaska">
 <Location Name="loc1">
  <Address>xyz</Address>
  <DateNTime>Saturday, Oct 2, 8pm</DateNTime>
 </Location>
 <Location Name="loc2">
  <Address>abc</Address>
  <DateNTime>Saturday, Oct 2, 10am</DateNTime>
 </Location>
</state>

這樣,我有50個州。 每個狀態都將出現在下拉列表中,並且在單擊狀態時,需要在網格視圖中顯示其地址和時間不同的位置。 這是代碼

private static IDictionary<string, Dictionary<string, Property>> dictionary;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        XDocument doc = XDocument.Load(Server.MapPath("test2.xml"));

       dictionary = doc.Root.Elements("state").ToDictionary(
            state => state.Attribute("name").Value,
            state => state.Elements("Location").ToDictionary(
                location => location.Attribute("Name").Value,
                Property));

        var x = dictionary.Keys;
        DropDownList1.DataSource = x;
        DropDownList1.DataBind();
 }
}
public void OnSelectedIndexChanged(Object sender, EventArgs e)
{

    GridView1.DataSource = from item in dictionary[DropDownList1.SelectedItem.Text]
                           select new { col1 = item.Key, col2 = item.Value };
    GridView1.DataBind();

}

public class Property
{
  public string address;
  public string datetime;
}

在這里,我不確切地知道如何聲明IDictionary並相應地檢索數據。 誰能解釋給我?

嘗試這個:

dictionary = doc.Root.Elements("state").ToDictionary(
                s => s.Attribute("name").Value,
                s => s.Elements("Location").ToDictionary(
                    loc => loc.Attribute("Name").Value,
                    loc => new Property
                    {
                        address = loc.Element("Address").Value,
                        datetime = loc.Element("DateNTime").Value
                    }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM