我创建了一个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");
答案 0 :(得分:1)
有关错误的更多信息会有所帮助。
但是,在我看来,我会说你在加载时总是写另一个“people”元素,即使文档已经存在。
你负载中的第二个If语句应该是。
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();
}