简体   繁体   中英

load saved XML file on form load event

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");

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM