我创建了一个 XML 文件,它保存得很好。不幸的是,保存的文件不会在我的表单加载事件中加载。我试图弄清楚出了什么问题,但我仍然不知道如何加载它。你能帮助我吗?
这是我的表单加载事件
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (!Directory.Exists(path + "\\iproject"))
{
Directory.CreateDirectory(path + "\\iproject");
}
if (!File.Exists(path + "\\iproject\\address.xml"))
{
File.Create(path + "\\iproject\\address.xml");
}
XmlTextWriter xw = new XmlTextWriter(path + "\\iproject\\address.xml", Encoding.UTF8);
xw.WriteStartElement("people");
xw.WriteEndElement();
xw.Close();
// load items wen form load event
XmlDocument xdoc = new XmlDocument();
xdoc.Load(path + "\\iproject\\address.xml");
foreach (XmlNode xnode in xdoc.SelectNodes("people/person"))
{
person p = new person();
p.name = xnode.SelectSingleNode("name").InnerText;
p.ipaddress = xnode.SelectSingleNode("ipaddress").InnerText;
people.Add(p);
listBox1.Items.Add(p.name);
}
这是我的保存事件
XmlDocument xdoc = new XmlDocument(); // saving listview data to xml file
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
xdoc.Load(path + "\\iproject\\address.xml");
XmlNode xnode = xdoc.SelectSingleNode("people");
xnode.RemoveAll();
foreach (person p in people)
{
XmlNode xTop = xdoc.CreateElement("person");
XmlNode xname = xdoc.CreateElement("name");
XmlNode xipaddress = xdoc.CreateElement("ipaddress");
xname.InnerText = p.name;
xipaddress.InnerText = p.ipaddress;
xTop.AppendChild(xname);
xTop.AppendChild(xipaddress);
xdoc.DocumentElement.AppendChild(xTop);
}
xdoc.Save(path + "\\iproject\\address.xml");