zoukankan      html  css  js  c++  java
  • 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 


  • 相关阅读:
    垃圾回收app冲击(一)
    本篇看似是一篇拍马屁的博客!但是真情实感!
    搜索建议
    冲击团队项目需求分析
    疫情分析冲击(五)
    疫情分析冲击(四)
    疫情分析冲击(三)
    疫情分析冲击(二)
    垃圾分类网站
    Android学习——singleInstance
  • 原文地址:https://www.cnblogs.com/hehaiquan/p/3180984.html
Copyright © 2011-2022 走看看