【发布时间】:2013-12-08 10:02:33
【问题描述】:
我是 C# 新手,但我正在尝试从这样的 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"/>
</senario>
<adventure Name ="Adventure 2">
<senario Name ="Senario 2">
<location Name="Location 2" Players="1"/>
</senario>
</adventure>
</adventure_path>
<adventure_path Name ="Adventure Path 2">
<adventure Name ="Adventure 3">
<senario Name ="Senario 3">
<location Name="Location 3" Players="1"/>
</senario>
<adventure Name ="Adventure 4">
<senario Name ="Senario 4">
<location Name="Location 4" Players="1"/>
</senario>
</adventure>
</adventure_path>
</adventures>
我想要做的是将名称属性加载到 itemlistbox 中选定的 Adventure_path 元素内的 Adventure 元素(“adventure 1”、“adventure 2”等)的 itemlistbox。我让选择部分工作并且加载到列表工作。不工作的是加载所有的冒险......
基本上发生的事情是 ListBox1 加载冒险路径都很好而且花花公子,我选择了其中一条冒险路径,而 ListBox2 加载了第一个冒险......就是这样。它不会加载冒险 2、3 或 4。所以这是应该加载所有冒险的代码-
private void lst_Adventure_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedItem = lst_Adventure.SelectedItem.ToString();
lst_Adventures.Items.Clear();
XDocument doc = new XDocument();
bool gotStatsXml = false;
try
{
doc = XDocument.Load("D:\\WpfApplication1\\WpfApplication1\\Adventures.xml");
gotStatsXml = true;
}
catch
{
gotStatsXml = false;
}
XElement selectedElement = doc.Descendants().Where(x => (string)x.Attribute("Name") == selectedItem).FirstOrDefault();
foreach (var docs in selectedElement.Descendants("adventure")) ;
{
XElement elements = selectedElement.Element("adventure");
string AdventuresPathName = elements.Attribute("Name").Value;
lst_Adventures.Items.Add(AdventuresPathName);
}
}
【问题讨论】:
-
附注 - 您的示例 xml 中没有关闭
</adventure>标记 -
啊,对,对不起。我会解决的。
-
以这种方式使用
catch是个坏主意。您应该只捕获特定的异常。