Reputation: 51
I have created an XML file and it saved perfectly. Unfortunately, the saved file will not load on my form load event. I tried to figure out what went wrong, but I still do not know how to load it. Can you help me?
Here is my form load event
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);
}
Here is my save event
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");
Upvotes: 0
Views: 803
Reputation: 3744
More information about the error would be helpful.
However, to my eye, I would say you are always writing another "people" element when you load, even if the document already exists.
Your second If statement in your load should be.
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();
}
Upvotes: 1