使用 C# 在 XML 中添加新用户注册信息





4.00/5 (1投票)
使用 C# 在 XML 中添加新的用户注册信息
引言
本技巧说明了如何在 XML 文档中添加新的用户信息,如果 XML 文档已存在,则将其追加到文档中。请先了解 XmlDocument
和 XmlNodeList
,以便更好地理解。
Using the Code
步骤 1:打开 Visual Studio -> 创建新网站 -> 点击空 ASP.NET 网站
步骤 2:在解决方案资源管理器中,右键单击添加新组件 -> 添加新的 Web Form
步骤 3:创建一个简单的注册表单,包含 用户名、年龄、手机号、密码 字段和一个 登录 按钮
步骤 4:添加一个名为 XMLRegister.xml 的 XML 文件
步骤 5:双击 登录 按钮
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)
{
//confirm Password
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();
//XmlDeclartion class used to declare XML prolog
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");
}
//Add Details
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);
}
关注点
- 使用
XmlWriter
或Xelement
以获得更好的性能
历史
这是我在 CodeProject 上的第一篇帖子,如果存在一些错误或缺陷,请在下面的评论区留言。XML 源代码和知识来自网络和 MSDN,我只是编写了一个演示应用程序来展示它们。版权所有。