c#操作xml增删改查

时间:2024-05-24 14:04:04

1.首先新建一个xml文件(Root是我写上的)

c#操作xml增删改查

2.

c#操作xml增删改查

3.直接上代码,更直观

(1)初始化xml

  

  /// <summary>
/// 初始化xml
/// </summary>
public void LoadXml()
{
xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("../wx.xml"));
}

(2)添加节点

 /// <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)修改节点中的某个属性

  /// <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中是否含有这个属性

 //判断是否已经写入到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格式而言要这样删除

  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格式是这样的
c#操作xml增删改查