Pages

Monday, May 20, 2013

How to add a new row of record to an XML file in ASP.NET

See the example first,
 XmlDocument xmldoc = new XmlDocument();
 xmldoc.Load(Server.MapPath("Users.xml"));
 XmlElement parentelement = xmldoc.CreateElement("users");
 XmlElement uname = xmldoc.CreateElement("UserName");
 XmlElement password = xmldoc.CreateElement("Password");
 XmlElement role = xmldoc.CreateElement("Role");
 uname.InnerText = txtUsrname.Text.Trim();
 password.InnerText = txtPass.Text.Trim();
 role.InnerText = txtRole.Text.Trim();
 parentelement.AppendChild(uname);
 parentelement.AppendChild(password);
 parentelement.AppendChild(role);
 xmldoc.DocumentElement.AppendChild(parentelement);
 xmldoc.Save(Server.MapPath("Users.xml"));
 lblresult.ForeColor = System.Drawing.Color.Green;
 lblresult.Text = " User "+txtUsrname.Text.Trim() + " added successfully";
 BindData();
The above example, XML file is using to keep authentication users list, it has three fields such as User Name, Password and Role. The above code add a new user to the XML file and shows the message. 

No comments:

Post a Comment