1.首先新建一个xml文件(Root是我写上的)
2.
3.直接上代码,更直观
(1)初始化xml
/// <summary> /// 初始化xml /// </summary> public void LoadXml() { xmlDoc = new XmlDocument(); xmlDoc.Load(Server.MapPath("../wx.xml")); }
(2)添加节点
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
/// <summary> /// 向xml中添加数据 /// </summary> public void AddElement(string FromUserName) { LoadXml(); XmlNode xmldocSelect = xmlDoc.SelectSingleNode("Root");//查找节点 XmlElement el = xmlDoc.CreateElement("Person"); //添加person节点 el.SetAttribute("name", FromUserName); //添加person节点的属性"name" el.SetAttribute("time", DateTime.Now.ToString()); xmldocSelect.AppendChild(el); xmlDoc.Save(Server.MapPath("../wx.xml")); }
(3)修改节点中的某个属性
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
/// <summary> /// 修改xml属性 /// </summary> /// <param name="FromUserName"></param> public void editXml(string FromUserName) { LoadXml(); XmlNodeList xnl = xmlDoc.DocumentElement.ChildNodes; foreach (XmlElement elementxml in xnl) { if (elementxml.Name == "Person") { if (elementxml.Attributes["name"].Value == FromUserName) { elementxml.Attributes["time"].Value = DateTime.Now.ToString(); } } } xmlDoc.Save(Server.MapPath("../wx.xml")); }
(4)判断xml中是否含有这个属性
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
//判断是否已经写入到xml中 public string IsExitXml(string FromUserName) { string datetime = ""; LoadXml(); XmlNodeList xnl = xmlDoc.DocumentElement.ChildNodes; foreach (XmlElement element in xnl) { if (element.Name == "Person") { if (element.Attributes["name"].Value ==FromUserName) { datetime = element.Attributes["time"].Value; } } } return datetime; }
(5)删除和修改差不多,对于我这个xml格式而言要这样删除
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public void DeleteXml(string FromUserName="dddddd") { LoadXml(); XmlNodeList xnl = xmlDoc.DocumentElement.ChildNodes; foreach (XmlElement elementxml in xnl) { if (elementxml.Name == "Person") { if (elementxml.Attributes["name"].Value == FromUserName) { XmlNode xmldocSelect = xmlDoc.SelectSingleNode("Root"); xmldocSelect.RemoveChild(elementxml); } } } xmlDoc.Save(Server.MapPath("../wx.xml")); }
(6)我的xml格式是这样的