• XML节点处理


    背景:有这样的需求,需要对另一个程序的config文件进行处理,这里做下记录。

    部分config文件如下:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
      </startup>
      <appSettings>
        <add key="StartDate" value="2019-01-01"/>
        <add key="CellID" value="10"/>
      </appSettings>
     
    </configuration>
    
    获取指定节点的值
            private string GetConfig(string nodeKey)
            {
                string result = string.Empty;
                XmlDocument xDoc = new XmlDocument();
                string path = @"../Debug/Debug/测试用发送数据机器人.exe.config";
                xDoc.Load(path);//加载xml文件
    
                XmlNode xNode;
                XmlElement xElem1;
    
                xNode = xDoc.SelectSingleNode("//appSettings");//获取指定的xml子节点
                xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + nodeKey + "']");//获取子节点中指定的子节点
                if (xElem1 != null)
                {
                    result = xElem1.Attributes[1].InnerXml;
                }
    
                return result;
            }
    
    修改指定节点的值
            public void ChangeConfig(string nodeKey,string nodeValue)
            {
                XmlDocument xDoc = new XmlDocument();
                string path = @"../Debug/Debug/测试用发送数据机器人.exe.config";
                xDoc.Load(path);//加载xml文件
    
                XmlNode xNode;
                XmlElement xElem1;
    
                xNode = xDoc.SelectSingleNode("//appSettings");//获取指定的xml子节点
                xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='"+nodeKey+"']");//获取子节点中指定的子节点
                //如果能获取到节点,就修改节点的value值
                if (xElem1 != null)
                {
                    xElem1.SetAttribute("value", nodeValue);//给节点中的value属性赋值(修改操作)
                }
                //如果不能获取到节点,就创建节点
                //else
                //{
                //    xElem2 = xDoc.CreateElement("add");
                //    xElem2.SetAttribute("key", "type");
                //    xElem2.SetAttribute("value", "teacher");
                //    xNode.AppendChild(xElem2);
                //}
                xDoc.Save(path);//保存xml文档
                Console.WriteLine("保存成功!");
            }
    
  • 相关阅读:
    pip安装flask问题解决
    GRE新东方推荐学习方法(2010年左右)
    使用eclipse IDE遇到的问题
    2014年互联网大会(商业价值,北京,7月)
    Indexing the World Wide Web: the Journey So Far阅读笔记
    Big Data Opportunities and Challenges(by周志华)论文要点
    spark常用算子总结
    使用Faster R-CNN做目标检测
    Oracle 性能调优 SQL_TRACE
    Oracle 性能调优 10053事件
  • 原文地址:https://www.cnblogs.com/peijia/p/11008802.html
Copyright © 2020-2023  润新知