【发布时间】:2017-07-20 16:15:31
【问题描述】:
我是 C# 新手,我正在尝试将 xml 文件中的一些数据加载到不同的列表框中。我已经尝试了一些东西,但似乎没有什么对我有用。我已经设法将列表框中的数据保存到 xml 文件中。
我尝试编写一些代码尝试将 xml 文件加载到列表框中:
private void OnLoad()
{
OpenFileDialog load = new OpenFileDialog();
//load.InitialDirectory = "c:\\";
load.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
load.FilterIndex = 2;
load.RestoreDirectory = true;
if (load.ShowDialog() == true)
{
using (StreamReader stream = new StreamReader(load.OpenFile()))
{
try
{
XmlDocument parsed = new XmlDocument();
parsed.Load(stream);
XmlNodeList foodList = parsed.GetElementsByTagName("Food");
for(int i = 0; i > foodList.Count; i++)
{
string var = elemList[i].Attributes["FoodName"].Value;
lb1.Items.Add(var);
}
catch(XmlException exception)
{
MessageBox.Show("The XML could not be read." + exception);
XmlDocument empty = new XmlDocument();
}
}
}
}
我的 XML 文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<ListBox>
<lb1>
<Food FoodName="*****" />
</lb1>
<lb2>
<Variable FoodName="****"/>
</lb2>
</ListBox>
lb1 和 lb2 是不同的列表框。我希望将 lb1 中的所有数据放入同名的列表框中,并将 lb2 中的所有数据放入同名的列表框中,等等。
【问题讨论】:
-
旁注:您可能想查看XmlSerializer,尽管有一些关于列表的特殊处理。看起来比你有的更容易。