首页 > 编程语言 >使用C#读写xml文件

使用C#读写xml文件

时间:2024-03-12 15:58:16浏览次数:18  
标签:xml node string C# 读写 XmlHelper var public out

由于xml文件的易读特性,使得它非常适合作为程序配置文件。和ini文件相比,xml文件可以实现列表等复杂参数配置,灵活性比较大。

使用C#读取xml文件,首先要加载xml文件获取XmlDocument对象,然后通过该对象获取XmlNode类型的根节点,之后再对根节点获取相应子节点的属性或值。写入xml文件时,获取对应的节点后设置其属性或者值即可。

本文对C#操作xml文件进行了封装处理,方便代码复用。

1、xml文件内容

<?xml version="1.0" encoding="utf-8"?>
<AppSettings>
  <!-- 调试模式:0-否,1-是 -->
  <DebugMode>0</DebugMode>
  <!-- FTP服务器参数 -->
  <FTP IP="127.0.0.1" Port="21" UserName="user" Password="user"/>
  <!-- 学生信息:Grade-年级,Class-班级 -->
  <Students Grade="1" Class="7">
    <!-- 学生:Name-姓名,Age-年龄 -->
    <Student Name="Name1" Age="6"/>
    <Student Name="Name2" Age="7"/>
    <Student Name="Name3" Age="7"/>
    <Student Name="Name4" Age="6"/>
  </Students>
</AppSettings>

2、XmlHelper.cs

public static class XmlHelper
{
    public static bool GetNodeInnerInt(XmlNode node, string xpath, out int value)
    {
        var text = node?.SelectSingleNode(xpath)?.InnerText.Trim();
        return int.TryParse(text, out value);
    }

    public static bool GetNodeInnerStr(XmlNode node, string xpath, out string value)
    {
        value = node?.SelectSingleNode(xpath)?.InnerText.Trim();
        return !string.IsNullOrEmpty(value);
    }

    public static void SetNodeInnerValue(XmlNode node, string xpath, string text)
    {
        var item = node?.SelectSingleNode(xpath);
        if (item != null)
        {
            item.InnerText = text;
        }
    }

    public static bool GetNodeAttributeInt(XmlNode node, string xpath, out int value)
    {
        var text = node?.Attributes?.GetNamedItem(xpath)?.Value.Trim();
        return int.TryParse(text, out value);
    }

    public static bool GetNodeAttributeStr(XmlNode node, string xpath, out string value)
    {
        value = node?.Attributes?.GetNamedItem(xpath)?.Value.Trim();
        return !string.IsNullOrEmpty(value);
    }

    public static void SetNodeAttributeValue(XmlNode node, string xpath, string text)
    {
        var item = node?.Attributes?.GetNamedItem(xpath);
        if (item != null)
        {
            item.Value = text;
        }
    }
}

3、XmlConfigManager.cs

internal class StudentInfo
{
    public string Name { get; set; }
    public int Age { get; set; }

    public StudentInfo(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

internal class ClassInfo
{
    public int Grade { get; set; }
    public int Class { get; set; }

    public List<StudentInfo> StudentInfoList { get; }

    public ClassInfo()
    {
        StudentInfoList = new List<StudentInfo>();
    }
}

internal sealed class XmlConfigManager
{
    public bool DebugMode { get; private set; } //调试模式
    public ClassInfo ClassInfo { get; } //班级信息

    #region 数据库参数

    public string DbIp { get; private set; } //数据库IP
    public int DbPort { get; private set; } = 1433; //数据库端口
    public string DbCatalog { get; private set; } //数据库名称
    public string DbUser { get; private set; } //数据库用户名
    public string DbPassword { get; private set; } //数据库密码

    public string ConnectionString =>
        $@"data source={DbIp},{DbPort};initial catalog={DbCatalog};persist security info=True;user id={DbUser};password={DbPassword}";

    #endregion

    private string _configName;
    private static readonly ILog Logger = LogManager.GetLogger(nameof(XmlConfigManager));

    /// <summary>
    /// 初始化配置
    /// </summary>
    public void LoadConfig(string configName)
    {
        _configName = configName;

        //Get Config file
        var info = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
        var xmlFilePath = Path.Combine(info.Parent?.FullName ?? string.Empty, _configName);

        //从配置文件读取数据
        var xmlDoc = new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFilePath);
        }
        catch (Exception e)
        {
            Logger.Error($@"加载配置文件[{configName}]失败:{e.Message}.");
            return;
        }

        var root = xmlDoc.SelectSingleNode("/AppSettings");
        LoadDebugModeConfig(root); //加载调试模式
        LoadDatabaseConfig(root); //加载数据库参数
        LoadClassInfoConfig(root); //加载班级信息
    }

    #region 获取参数

    private void LoadDebugModeConfig(XmlNode root)
    {
        try
        {
            var node = root?.SelectSingleNode("Common");
            if (XmlHelper.GetNodeInnerStr(node, "DebugMode", out var str))
            {
                DebugMode = str == "1";
            }
        }
        catch (Exception e)
        {
            Logger.Error($@"加载调试模式异常:{e.Message}.");
        }
    }

    private void LoadDatabaseConfig(XmlNode root)
    {
        try
        {
            var node = root?.SelectSingleNode("Database");
            if (XmlHelper.GetNodeAttributeStr(node, "Ip", out var ip))
            {
                DbIp = ip;
            }

            if (XmlHelper.GetNodeAttributeInt(node, "Port", out var port))
            {
                DbPort = port;
            }

            if (XmlHelper.GetNodeAttributeStr(node, "Catalog", out var catalog))
            {
                DbCatalog = catalog;
            }

            if (XmlHelper.GetNodeAttributeStr(node, "User", out var user))
            {
                DbUser = user;
            }

            if (XmlHelper.GetNodeAttributeStr(node, "Password", out var password))
            {
                DbPassword = password;
            }
        }
        catch (Exception e)
        {
            Logger.Error($@"加载数据库参数异常:{e.Message}.");
        }
    }

    private void LoadClassInfoConfig(XmlNode root)
    {
        try
        {
            var node = root?.SelectSingleNode("ClassInfo");
            if (XmlHelper.GetNodeAttributeInt(node, "Grade", out var val))
            {
                ClassInfo.Grade = val;
            }

            if (XmlHelper.GetNodeAttributeInt(node, "Class", out val))
            {
                ClassInfo.Class = val;
            }

            var nodeList = node?.SelectNodes("Student");
            if (nodeList == null || nodeList.Count == 0)
            {
                return;
            }

            foreach (XmlNode item in nodeList)
            {
                if (XmlHelper.GetNodeAttributeStr(item, "Name", out var str) &&
                    XmlHelper.GetNodeAttributeInt(item, "Age", out val))
                {
                    ClassInfo.StudentInfoList.Add(new StudentInfo(str, val));
                }
            }
        }
        catch (Exception e)
        {
            Logger.Error($@"加载班级信息异常:{e.Message}.");
        }
    }

    #endregion

    #region 设置参数

    public void SetDatabaseConfig(string ip, string catalog, string user, string password)
    {
        DbIp = ip;
        DbCatalog = catalog;
        DbUser = user;
        DbPassword = password;

        //Get Config file
        var info = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
        var xmlFilePath = Path.Combine(info.Parent?.FullName ?? string.Empty, _configName);

        //从配置文件读取数据
        var xmlDoc = new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFilePath);
            var node = xmlDoc.SelectSingleNode("/AppSettings/Database");
            XmlHelper.SetNodeAttributeValue(node, "Ip", ip);
            XmlHelper.SetNodeAttributeValue(node, "Catalog", catalog);
            XmlHelper.SetNodeAttributeValue(node, "User", user);
            XmlHelper.SetNodeAttributeValue(node, "Password", password);
            xmlDoc.Save(xmlFilePath);
        }
        catch (Exception e)
        {
            Logger.Error($@"设置数据库参数失败:{e.Message}.");
            throw;
        }
    }

    #endregion

    #region 单例模式

    private static XmlConfigManager _instance;

    private static readonly object LockInstanceHelper = new object();

    private XmlConfigManager()
    {
        ClassInfo = new ClassInfo();
    }

    public static XmlConfigManager Instance
    {
        get
        {
            if (_instance != null)
            {
                return _instance;
            }

            lock (LockInstanceHelper)
            {
                _instance = _instance ?? new XmlConfigManager();
            }

            return _instance;
        }
    }

    #endregion
}

标签:xml,node,string,C#,读写,XmlHelper,var,public,out
From: https://www.cnblogs.com/xhubobo/p/18068488

相关文章

  • 基于Vue(提供Vue2/Vue3版本)和.Net Core前后端分离、跨平台的快速开发框架
    前言今天大姚给大家推荐一款基于Vue(提供Vue2/Vue3版本)和.NetCore前后端分离、开源免费(MITLicense)、强大、跨平台的快速开发框架,并且框架内置代码生成器(解决重复性工作,提高开发效率),支持移动端(iOS/Android/H5/微信小程序):Vue.NetCore。提高开发生产效率、避免996可以考虑试试这......
  • 关于failed to load resource 问题的处理
    问题:c++做插件,写了一个nativeclass,继承于ue的类ActorComponent,而蓝图里也继承了这个c++class,都在插件里,每次打开的时候就有这个错误:之前的解决办法,复制文件到桌面上,然后删除本地这个文件,涉及到这个类的在做做改动,工作量挺大的,之前基于这个插件做了不少逻辑,所以要改动很久。......
  • 2024-03-11 leetcode写题记录
    目录2024-03-11leetcode写题记录206.反转链表题目链接题意解法876.链表的中间结点题目链接题意解法2024-03-11leetcode写题记录206.反转链表题目链接206.反转链表题意给你单链表的头节点head,请你反转链表,并返回反转后的链表。解法链表反转板子题,特殊处理下一个点......
  • 将Asp.net Core 微服务容器部署到 Kubernetes
    将微服务容器部署到KubernetesKubernetes会为你运行容器,需要通过YAML文件描述希望Kubernetes执行的操作,在Kubernetes上部署和运行后端服务简单操作如下步骤安装Kubernetes工具和实现我们需要同时安装kubectl工具和Kubernetes实现按照参考:https://www.cnblogs.co......
  • 英伟达CEO黄仁勋:10年内算力将提升100万倍
    过去10年AI的算力增加了100万倍,未来10年,英伟达还会把深度学习的计算能力再提高100万倍,让AI计算设备不断训练、推理、学习、应用,并持续改进,未来不断将超级AI转变为现实,NVIDIA英伟达CEO黄仁勋表示,未来不断推动技术进步,将计算的边际成本降低到接近零,让更多人使用上AI算力。 ......
  • [Rust] Thread 3: move keyword to resolve borrowing problem for closure
    Weofteruse movewithclosurespassedto thread::spawnbecasetheclosurewillthentakeownershipofthevaluesitusesfromtheenvironment,thustransferringowershopofthosevaluesfromonethreadtoanother. Thefollowingcodewon'twork:use......
  • The 2023 CCPC (Qinhuangdao) Onsite (The 2nd Universal Cup. Stage 9: Qinhuangdao)
    Preface完全披萨,最害怕的一集,2h过了5题后开始大坐牢环节徐神开D感觉是个巨复杂的字符串讨论题,一不注意就码了200+行然后我和祁神在下面讨论得出了I的做法,虽然是个DS题但上去写的时候一点自信没有最后摸了半天到比赛结束后1min才调出样例,赛后又调了半小时左右才过了这题唉这就......
  • c语言不可不说的一件事——进制之间的转化
    进制之间的转换二进制转换二进制转换为十进制10111010.101转换方法:个位数是乘以2的0次方从小数点开始分割,(小数点前从右往左,小数点后从左往右)乘以2的对应次方(从0开始取),最后相加二进制转换为八进制转换方法:取三合一凑不够三位数就补0与八进制转换表一一对应从小数点......
  • abc336F 旋转矩阵谜题
    有一个大小为W*H的矩阵,每个格子里分别有1~W*H的某个数字,对应1~W*H的一个排列。每次可以选择大小为(W-1)*(H-1)的子矩阵旋转180度。给定初始状态,问20步以内是否可以将它还原?如果可以,输出最小步数,否则输出-1。3<=H,W<=8;1<=a[i][j]<=H*W;a[i][j]各不相等bfs搜索,由于每一步都......
  • CentOS8安装postgresql13和postgis
    CentOS8安装postgresql13和postgis这里使用的是8.5.2111操作系统版本,首先解决一下网络源的问题。检验dnf是否能正常使用,顺便安装wgetdnf-yinstallwget 一、安装postgresql131、配置postgresql官网提供的网络源dnfinstall-yhttps://download.postgre......