using System;
using System.Xml;
/// <summary>
/// 控制XML文件的操作
/// </summary>
public class xmlManager
{
private XmlDocument xmlDoc;
private string userid;
private string name;
private string password;
private string phone;
private string city;
public xmlManager()
{
}
public xmlManager(string myid,string myname,string mypass,string myphone,string mycity)
{
this.userid = myid;
this.name = myname;
this.password = mypass;
this.phone = myphone;
this.city = mycity;
}
/// <summary>
/// 加载XML文件的方法
/// </summary>
/// <param name="xmlfile">XML文件路径</param>
private void LoadXml()
{
xmlDoc = new XmlDocument();
xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath("XMLFile.xml"));
}
public void AddNode()
{
//加载文档
LoadXml();
//选择根节点
XmlNode xmldocboot = xmlDoc.SelectSingleNode("userinfo");
//开始添加节点及节点的属性
XmlElement ele = xmlDoc.CreateElement("user");
XmlElement ele1 = xmlDoc.CreateElement("id");
ele1.InnerText = userid;
XmlElement ele2 = xmlDoc.CreateElement("name");
ele2.InnerText = name;
XmlElement ele3 = xmlDoc.CreateElement("password");
ele3.InnerText = password;
XmlElement ele4 = xmlDoc.CreateElement("phone");
ele4.InnerText = phone;
XmlElement ele5 = xmlDoc.CreateElement("city");
ele5.InnerText = city;
ele.AppendChild(ele1);
ele.AppendChild(ele2);
ele.AppendChild(ele3);
ele.AppendChild(ele4);
ele.AppendChild(ele5);
//将节点保存到根节点下
xmldocboot.AppendChild(ele);
//保存XML文件的修改-此处要注意,如果文件保存在系统盘,还要考虑用户权限的问题。
xmlDoc.Save(System.Web.HttpContext.Current.Server.MapPath("XMLFile.xml"));
}
}
后台调用:
//初始化XML操作类
xmlManager myxml = new xmlManager(值1,值2,值3,...,);
//执行添加命令
myxml.AddNode();