C# 从孩子的描述者那里得到描述
所以我有一段代码,它应该让我的xml文件在选择前一个元素后读取每个子元素的属性。这是我正在使用的xml-C# 从孩子的描述者那里得到描述,c#,xml,wpf,descendant,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">
<?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>
我刚刚用您提供的xml尝试了您的代码,发现了一些缺陷。如果我没有误解您的期望,当这些问题得到纠正时,您的代码将按预期运行: senario的开始标记与结束标记场景不匹配。如果您将开始标记更改为scenario,请不要忘记在foreach中将senario更改为scenario。 如果我没有误解变量,selectedAdventure应该与selectedAdventure而不是selectedItem匹配
我已经编辑了你的标题。请看,如果共识是否定的,他们不应该。哦,对不起,我是这个网站的新手。每个页面的顶部都有一个很好的帮助按钮。谢谢,但是你知道有什么方法可以帮助我解决这个问题吗?
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);
}
}
}