【发布时间】:2013-12-08 21:21:02
【问题描述】:
所以我有这段代码应该让我的 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);
}
}
}
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
抱歉,我是这个网站的新手
-
每页顶部都有一个非常漂亮的“帮助”按钮。
-
谢谢,但是你知道有什么方法可以帮助我解决我的问题吗?
标签: c# xml wpf descendant