zoukankan      html  css  js  c++  java
  • .NET开发笔记--对config文件的操作(3)

    1、添加新节点前进行判断看是否已存在相同的属性值,若存在进行更新,不存在则进行添加操作。

           protected bool AddPizza()
            {
                //初始化id  
                int newId;
                string filePath = HttpContext.Current.Server.MapPath("XMLFile.xml");
                //创建XML文件对象的实例doc  
                XmlDocument doc = new XmlDocument();
                //加载XML文件  
                doc.Load(filePath);
                //获取结点Pizza下的所有子结点  
                XmlNodeList nodeList = doc.SelectSingleNode("Pizza").ChildNodes;
                bool isExist = true;
                foreach (XmlElement xe in nodeList)
                {
                    isExist = xe.Attributes["size"].Value == tbPizzaSize.Text;
                    if (isExist)
                    {
                        xe.SetAttribute("price", tbPizzaPrice.Text);
                        doc.Save(filePath);
                    }
                 
                }
                if (!isExist)
                {
                    if (nodeList.Count > 0)
                    {
    
                        //查找最后一个结点的id  
                        newId = Convert.ToInt32(doc.DocumentElement.SelectSingleNode("/Pizza/Pizzas[last()]").Attributes["id"].Value) + 1;
                        //创建一个新的xml元素  
                        XmlElement Pizzas = doc.CreateElement("Pizzas");
                        //创建xml属性  
                        XmlAttribute id = doc.CreateAttribute("id");
                        XmlAttribute size = doc.CreateAttribute("size");
                        XmlAttribute price = doc.CreateAttribute("price");
                        //给xml属性赋值  
                        id.Value = newId.ToString();
                        size.Value = tbPizzaSize.Text;
                        price.Value = tbPizzaPrice.Text;
                        //给结点赋值  
                        Pizzas.InnerText = tbPizzaName.Text;
                        //把属性值添加到元素结点里  
                        Pizzas.Attributes.Append(id);
                        Pizzas.Attributes.Append(size);
                        Pizzas.Attributes.Append(price);
                        //把元素结点添加到XMl文件里  
                        doc.DocumentElement.AppendChild(Pizzas);
                        //保存XML文件  
                        doc.Save(filePath);
                    }
                    else
                    {
                        newId = 1;
                    }
                }
                return true;
            }
  • 相关阅读:
    Arduino语法-变量和常量
    Arduino-函数库和程序架构介绍
    第十章浮力题汇总
    pyqt5-按钮基类-QAbstractButton
    在Windows上安装Arduino-IDE
    Arduino-接口图
    python-文件及文件夹操作
    Qt WebRTC demo
    多线程使用信号量sem_init,sem_wait,sem_post
    华为公司内部培训资料_介绍RTSP的消息、信令等
  • 原文地址:https://www.cnblogs.com/kennyliu/p/3384907.html
Copyright © 2011-2022 走看看