Dylan Morrison
Dylan Morrison

Reputation: 15

How to add more than one user to an xml file

I'm new to C# and currently trying to create a simple login screen using windows forms. The program takes the forms input and saves the username and password to an XML file. I'm just wondering how I can save more than one user instead of the previous users data being overwritten when I save a new user. This is the code I'm currently using.

    {
        XmlTextWriter write = new XmlTextWriter("XML.xml", Encoding.UTF8);
        write.WriteStartElement("USER");
        write.WriteStartElement("username");
        write.WriteString(textBox1.Text);
        write.WriteEndElement();
        write.WriteStartElement("passsword");
        write.WriteString(textBox2.Text);
        write.WriteEndElement();
        write.WriteEndElement();
        write.Close();
    }

Upvotes: 0

Views: 284

Answers (1)

M. Usman
M. Usman

Reputation: 111

Try this:

XmlDocument xmlDoc = new XmlDocument();
        string filePath = Path.Combine(@"C:\assets\" + "users.xml");
        XmlNode usersNode;

        if (File.Exists(filePath))
        {
            xmlDoc.Load(filePath);
            usersNode = xmlDoc.SelectSingleNode(@"Users");
        }
        else
        {
            usersNode = xmlDoc.CreateElement("Users");
            xmlDoc.AppendChild(usersNode);
        }

        XmlElement user = xmlDoc.CreateElement("User");
        XmlElement userName = xmlDoc.CreateElement("UserName");
        XmlElement pass = xmlDoc.CreateElement("Pass");

        userName.InnerText = "TestUser";
        pass.InnerText = "TemPass";

        user.AppendChild(userName);
        user.AppendChild(pass);
        usersNode.AppendChild(user);

        xmlDoc.Save(filePath);

Upvotes: 1

Related Questions