zoukankan      html  css  js  c++  java
  • c#操作xml(读,写)

    c#读xml文件:

    //不用说,是建立对象,读取文件
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load("haha.xml");
    //获取bookstore节点的所有子节点
    XmlNodeList nodeList = xmlDoc.SelectSingleNode("conf").ChildNodes;
    //有多少个子节点
    int configNum = nodeList.Count;
    //遍历所有子节点
    foreach (XmlNode fir1 in nodeList)
    {
        //将子节点类型转换为XmlElement类型
        XmlElement xmle = (XmlElement)fir1;
        //同上,再遍历一遍,如果下面还有子节点,层层遍历
        XmlNodeList nodeList2 = xmle.ChildNodes;
        foreach (XmlNode fir2 in nodeList2)
        {
            if (fir2.Name == "ipaddress")
            {
               //你的变量 = fir2.InnerText.ToString();
            }
            if (fir2.Name == "ipname")
            {
                //你的变量 = fir2.InnerText.ToString();
            }
        }
    }
    //xmle声明下面也可以加入这句,代表取属性为id的节点
    if (xe.GetAttribute("id") == 你的参数)
    ///使用完后可以返回个数组。 

    上面的代码稍微修改一下,就可以用作修改xml了,很简单:

    //开头都一样到了下面要注意
    //xmle声明下面也可以加入这句,代表取属性为id的节点
    if (xe.GetAttribute("id") == 你的参数)
    {
        foreach (XmlNode fir1 in nodeList)
        {
            XmlElement xmle = (XmlElement)fir1;
            XmlNodeList nodeList2 = xmle.ChildNodes;
            foreach (XmlNode fir2 in nodeList2)
            {
                if (fir2.Name == "ipaddress")
                {
                    //注意,这里改了fir2.InnerText = 你的变量;
                }
            }
        }
        break;
    }
    //最后不要忘记保存。
    xmlDoc.Save("ping.xml");
  • 相关阅读:
    Leetcode:169. 多数元素
    关系数据库
    数据库系统概述——简单总结
    Leetcode:1305. 两棵二叉搜索树中的所有元素
    Leetcode春季打卡第四天:994. 腐烂的橘子
    临界区和临界资源的关系
    线程2.线程的应用场景
    线程
    linux下的进程控制
    Go中的错误处理
  • 原文地址:https://www.cnblogs.com/blazeq/p/1830995.html
Copyright © 2011-2022 走看看