从子后代获取属性

时间:2013-12-08 21:21:02

标签: c# xml wpf descendant

所以我有这个代码,它应该让我的xml文件在选择前一个元素后读出每个后代元素的属性。这是我正在使用的xml -

<?xml version="1.0" encoding="utf-8" ?> 
<adventures>
  <adventure_path Name ="Adventure Path 1">
    <adventure Name ="Adventure 1">
      <senario Name ="Senario 1">
        <location Name="Location 1" Players="1"/>
        <location Name="Location 2" Players="1"/>
      </scenario>
      <senario Name ="Senario 2">
        <location Name="Location 3" Players="1"/>
        <location Name="Location 4" Players="1"/>
      </scenario>
    </adventure>
    <adventure Name="Addventure 2">
      <senario Name ="Senario 3">
        <location Name="Location 5" Players="1"/>
        <location Name="Location 6" Players="1"/>
      </scenario>
    </adventure>
  </adventure_path>
  <adventure_path Name ="Adventure Path 2">
    <adventure Name ="Adventure 3">
      <senario Name ="Senario 4">
        <location Name="Location 7" Players="1"/>
        <location Name="Location 8" Players="1"/>
      </scenario>
      <senario Name ="Senario 5">
        <location Name="Location 9" Players="1"/>
        <location Name="Location 10" Players="1"/>
      </scenario>
    </adventure>
  </adventure_path>
</adventures>

所以基本上应该发生什么,程序列出了listbox1中的所有冒险路径,我选择了一条冒险路径。该程序列出了所选冒险路径中的所有冒险,我选择一个。最后,该程序列出了所选冒险中的所有场景。目前发生的事情是它会完美地完成前两个列表,但是当我在第二个列表中选择冒险时,我似乎无法列出任何场景。它没有崩溃,只是没有列出它们。任何帮助都会很棒,这是我应该制作所有场景列表的代码。

 private void lst_Adventures_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string selectedItem = lst_Adventure.SelectedItem.ToString();
    string selectedAdventure = lst_Adventures.SelectedItem.ToString();

    lst_Senarios.Items.Clear();

    System.Console.WriteLine(selectedItem);

    XDocument doc = new XDocument();

    doc = XDocument.Load("D:\\WpfApplication1\\WpfApplication1\\Adventures.xml");

    XElement selectedElement = doc.Descendants().Where(x => (string)x.Attribute("Name") == selectedItem).FirstOrDefault();
    XElement selectedAdventures = selectedElement.Descendants().Where(x => (string)x.Attribute("Name") == selectedItem).FirstOrDefault();

    if (selectedAdventures != null)
    {
        foreach (var docs in selectedAdventures.Elements("senario"))
        {
            string AdventuresPathName = docs.Attribute("Name").Value;
            lst_Adventures.Items.Add(AdventuresPathName);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我刚刚用你提供的xml尝试了你的代码,我注意到了一些缺陷。当这些得到纠正后,您的代码将按预期运行(如果我不会误解您的期望):

  1. senario的打开标记与结束标记scenario不匹配。如果您将开头标记更改为scenario,请不要忘记在foreach中将“senario”更改为“scenario”。
  2. selectedAdventures应与selectedAdventure匹配,而不是selectedItem(如果我不误解变量)