繁体   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