1.首先新建一个xml文件(Root是我写上的)
2.
3.直接上代码,更直观
(1)初始化xml
/// <summary> /// 初始化xml /// </summary> public void LoadXml() { xmlDoc = new XmlDocument(); xmlDoc.Load(Server.MapPath("../wx.xml")); }
(2)添加节点
class="code_img_closed" src="/Upload/Images/2013102417/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('5fcce7ed-91d3-4d6e-a661-9519580e62ea',event)" src="/Upload/Images/2013102417/2B1B950FA3DF188F.gif" alt="" />/// <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")); }View Code
(3)修改节点中的某个属性
/// <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")); }View Code
(4)判断xml中是否含有这个属性
//判断是否已经写入到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; }View Code
(5)我的xml格式是这样的
(6)删除和修改差不多,只是把属性改为
xe.RemoveAttribute("name");//删除genre属性