C#操作xml文件进行增、删、改

进行操作的xml文件:

products.xml 

<?xml version="1.0" encoding="utf-8"?>
<products>
<product name="apple" price="3.50"/>
<product name="banana" price="2.00"/>
</products>  
View Code 

增加节点:

XmlDocument doc = new XmlDocument();
doc.Load("products.xml");
XmlNode xn = doc.SelectSingleNode("products");
XmlElement xe = doc.CreateElement("product");
xe.SetAttribute("name","haha");
xe.SetAttribute("price","13.20");
xn.AppendChild(xe);
doc.Save("products.xml")
View Code 

修改节点属性值:

XmlDocument doc = new XmlDocument();
doc.Load("products.xml");
XmlNode xn = doc.SelectSingleNode("products");
XmlNodeList xnList = xn.ChildNodes;
if(xnList.Count > 0)
{
    for(int i = xnList.Count - 1; i >= 0;i--)
    {
         XmlElement xe = (XmlElement)xnList.Item(i);
         if(xe.Attributes["name"].Value == "banana")
         {
             xe.SetAttribute("price","1111");
         break;    
         }
    }
    doc.Save("products.xml")
View Code 

 删除节点:

XmlDocument doc = new XmlDocument();
doc.Load("products.xml");
XmlNode xn = doc.SelectSingleNode("products");
XmlNodeList xnList = xn.ChildNodes;
if(xnList.Count > 0)
{
    for(int i = xnList.Count - 1; i >= 0;i--)
    {
         XmlElement xe = (XmlElement)xnList.Item(i);
         if(xe.Attributes["name"].Value == "banana")
         {
             xn.RemoveChild(xe);
         }
    }
    doc.Save("products.xml")
View Code 


原文地址:https://www.cnblogs.com/hehaiquan/p/3180984.html