Introduction
This tip states how you add new user information in XML document if XML document already exists, then append in it. Please gain some knowledge about XmlDocument
and XmlNodeList
for better understanding.
Using the Code
Step 1: Open Visual Studio -> Create New Website-> click Empty ASP.NET website
Step 2: In Solution Explorer, right click add new component-> Add new webform
Step 3: Create a simple registration form with Username, Age ,Mobile, Password Fields and a Login Button
Step 4: Add an XML file named XMLRegister.xml
Step 5: Double click on Login Button
public partial class Register : System.Web.UI.Page
{
static string name=string.Empty;
static string pswd=string.Empty;
static string age=string.Empty;
static string mobile=string.Empty;
static XmlNode root;
static XmlNode xn; XmlDocument xdoc;
protected void Page_Load(object sender, EventArgs e)
{
lblErrorPswd.Visible = false;
name = txtUname.Text;
if(Page.IsPostBack)
{
if (txtPswd.Text == txtCpswd.Text)
{
pswd = txtPswd.Text;
age = txtAge.Text;
mobile=txtMobile.Text;
}
else
{
lblError.Visible=True;
}
}
}
protected void butRegister_Click(object sender, EventArgs e)
{
string xmlpath = @"C:\Users\XMlRegister.xml";
xdoc = new XmlDocument();
XmlDeclaration xdeclartion = xdoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
root = xdoc.CreateElement("logindetails");
xdoc.AppendChild(root);
AppendXml(root);
xdoc.Save(xmlpath);
Response.Redirect("login.aspx");
}
protected void AppendXml(XmlNode root)
{
XmlNode person = xdoc.CreateElement("person");
root.AppendChild(person);
XmlNode uname = xdoc.CreateElement("uname");
uname.InnerText = name;
person.AppendChild(uname);
XmlNode psswd = xdoc.CreateElement("pswd");
psswd.InnerText = pswd;
person.AppendChild(psswd);
XmlNode agge = xdoc.CreateElement("age");
agge.InnerText = age;
person.AppendChild(agge);
XmlNode mob = xdoc.CreateElement("mobile");
mob.InnerText = mobile;
person.AppendChild(mob);
}
Points of Interest
- Use
XmlWriter
or Xelement
for better performance
History
This is my first post on CodeProject, if there are some errors or flaws, please write in the comments section below. The XML source data and the knowledge comes from the web and MSDN, I just wrote a demo app to show them. No copyright reserved.