直接解析XML文件

1、System.Xml.Linq命名空间下提供可以使用linq查询的类,使用linq to xml读取也很方便。

2、还可以使用System.Xml.Serialization类的DeSerialize方法直接实例化。

https://docs.microsoft.com/zh-cn/dotnet/api/system.xml.serialization.xmlserializer.deserialize?view=netcore-2.2

在直接读取文件的时候由于手动getAttribute很麻烦,而且容易出错,attribute可以参考log4net的方式,全部做成宏定义:

使用.Net提供的的方式(ConfigurationManager类,支持.Net Core 2)

特别说明:

using System.Configuration 之后可能还要手动勾选,如下图:

使用.Net提供的方法读取有时候会很方便,可以直接将配置信息填写在app.config文件中例如下面的配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup> <appSettings>
<add key="name" value="kun"/>
<add key="name2" value="kun"/>
</appSettings> <connectionStrings>
<add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" />
</connectionStrings> </configuration>

读取的时候:

static void ReadAllSettings()
{
try
{
var appSettings = ConfigurationManager.AppSettings; if (appSettings.Count == 0)
{
Console.WriteLine("AppSettings is empty.");
}
else
{
foreach (var key in appSettings.AllKeys.Where((key) => key == "name"))
{
Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);
}
}
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
} static void ReadSetting(string key)
{
try
{
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key] ?? "Not Found";
Console.WriteLine(result);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}

读取数据库连接信息也可以只用一句代码:

var connectionString = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString;

对于这种简单key/Value方式的配置,使用ConfigurationManager类还是很方便的。

自定义配置

配置比较复杂呢?当然App.config文件也支持自定义,就是用起来比较复杂,需要手动写一个有各种限制的类。

<?xml version="1.0" encoding="utf-8" ?>
<configuration> <configSections>
<section name="sampleSection" type="System.Configuration.SingleTagSectionHandler" />
</configSections> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup> <appSettings>
<add key="name" value="kun"/>
<add key="name2" value="kun"/>
</appSettings> <connectionStrings>
<add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" />
</connectionStrings> <sampleSection setting1="Value1"
setting2="value two"
setting3="third value">
</sampleSection> </configuration>

上面sampleSection 就是自定义的配置,使用起来的话需要手动实现下面这个类(微软官方的示例):

// Define a custom section.
// The CustomSection type allows to define a custom section
// programmatically.
public sealed class CustomSection :
ConfigurationSection
{
// The collection (property bag) that contains
// the section properties.
private static ConfigurationPropertyCollection _Properties; // Internal flag to disable
// property setting.
private static bool _ReadOnly; // The FileName property.
private static readonly ConfigurationProperty _FileName =
new ConfigurationProperty("fileName",
typeof(string),"default.txt",
ConfigurationPropertyOptions.IsRequired); // The MaxUsers property.
private static readonly ConfigurationProperty _MaxUsers =
new ConfigurationProperty("maxUsers",
typeof(long), (long)1000,
ConfigurationPropertyOptions.None); // The MaxIdleTime property.
private static readonly ConfigurationProperty _MaxIdleTime =
new ConfigurationProperty("maxIdleTime",
typeof(TimeSpan), TimeSpan.FromMinutes(5),
ConfigurationPropertyOptions.IsRequired); // CustomSection constructor.
public CustomSection()
{
// Property initialization
_Properties =
new ConfigurationPropertyCollection(); _Properties.Add(_FileName);
_Properties.Add(_MaxUsers);
_Properties.Add(_MaxIdleTime);
} // This is a key customization.
// It returns the initialized property bag.
protected override ConfigurationPropertyCollection Properties
{
get
{
return _Properties;
}
} private new bool IsReadOnly
{
get
{
return _ReadOnly;
}
} // Use this to disable property setting.
private void ThrowIfReadOnly(string propertyName)
{
if (IsReadOnly)
throw new ConfigurationErrorsException(
"The property " + propertyName + " is read only.");
} // Customizes the use of CustomSection
// by setting _ReadOnly to false.
// Remember you must use it along with ThrowIfReadOnly.
protected override object GetRuntimeObject()
{
// To enable property setting just assign true to
// the following flag.
_ReadOnly = true;
return base.GetRuntimeObject();
} [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
MinLength = 1, MaxLength = 60)]
public string FileName
{
get
{
return (string)this["fileName"];
}
set
{
// With this you disable the setting.
// Remember that the _ReadOnly flag must
// be set to true in the GetRuntimeObject.
ThrowIfReadOnly("FileName");
this["fileName"] = value;
}
} [LongValidator(MinValue = 1, MaxValue = 1000000,
ExcludeRange = false)]
public long MaxUsers
{
get
{
return (long)this["maxUsers"];
}
set
{
this["maxUsers"] = value;
}
} [TimeSpanValidator(MinValueString = "0:0:30",
MaxValueString = "5:00:0",
ExcludeRange = false)]
public TimeSpan MaxIdleTime
{
get
{
return (TimeSpan)this["maxIdleTime"];
}
set
{
this["maxIdleTime"] = value;
}
} }

参考:

https://docs.microsoft.com/zh-cn/dotnet/api/system.configuration.configurationmanager?view=netframework-4.7.2

https://docs.microsoft.com/zh-cn/dotnet/api/system.configuration.configurationsection?view=netframework-4.7.2

https://blog.csdn.net/aojiancc2/article/details/21618299

.Net 读取配置文件 xml的更多相关文章

  1. 读取配置文件包含properties和xml文件

    读取properties配置文件 /** * 读取配置文件 * @author ll-t150 */ public class Utils { private static Properties pr ...

  2. python读取配置文件(ini、yaml、xml)

    python读取配置文件(ini.yaml.xml)  

  3. bean.xml配置数据源和读取配置文件配置数据源

    一.bean.xml配置数据源 bean.xml装配bean,依赖注入其属性的时候,对应实体类中属性一定要有set方法, 二.读取配置文件配置数据源 1.配置文件 bean.xml配置: classp ...

  4. 解决IntelliJ IDEA无法读取配置文件的问题

    解决IntelliJ IDEA无法读取配置文件的问题 最近在学Mybatis,按照视频的讲解在项目的某个包里建立配置文件,然后读取配置文件,但是一直提示异常. 读取配置文件的为官方代码: String ...

  5. java 4种方式读取配置文件 + 修改配置文件

    版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[-] 方式一采用ServletContext读取读取配置文件的realpath然后通过文件流读取出来 方式二采用ResourceB ...

  6. ASP.NET Core开发-读取配置文件Configuration

    ASP.NET Core 是如何读取配置文件,今天我们来学习. ASP.NET Core的配置系统已经和之前版本的ASP.NET有所不同了,之前是依赖于System.Configuration和XML ...

  7. Java 利用 ByteArrayOutputStream 和 ByteArrayInputStream 避免重复读取配置文件

    最近参与了github上的一个开源项目 Mycat,是一个mysql的分库分表的中间件.发现其中读取配置文件的代码,存在频繁多次重复打开,读取,关闭的问题,代码写的很初级,稍微看过一些框架源码的人,是 ...

  8. ASP.NET读取配置文件发送邮件

    之前写过一篇文章C#使用SMTP发送邮件 后来做了改进,改成读取独立的配置文件,本文只记录读取配置文件的部分,发送部分见上面的链接. 读取配置文件C#代码: using System; using S ...

  9. 通过读取配置文件App.config来获取数据库连接字符串

    有两种方式://通过读取配置文件来获取连接字符串 第一种方式: App.config 文件的格式: <?xml version="1.0" encoding="ut ...

随机推荐

  1. Nestjs 序列化(Serialization)

    文档 在发送实际响应之前,Serializers为数据操作提供了干净的抽象层.例如,应始终从最终响应中排除敏感数据(如用户密码) λ yarn add class-transformer cats.e ...

  2. Yarn Node Labels

    Yarn Node Labels + Capacity-Scheduler 在yarn-site.xml中开启capacity-schedule yarn-site.xml <property& ...

  3. Tomcat部署工程需注意的三点

    Tomcat部署工程需注意: 1.如果该服务器是第一安装Tomcat,则各位大人应将该Tomcat的解压文件夹 backup 一份,已被不时之用.2.部署时应当注意修改Tomcat安装目录中conf文 ...

  4. JS常见的字符串操作

    1.charAt() 获取字符串指定位置的字符    用法:strObj是字符串对象,index是指定的位置,(位置从0开始数) strObj.charAt(index) 2. indexOf() 方 ...

  5. python入门以及接口自动化实践

    一.Python入门必备基础语法# 标识符:python中我们自己命名的都是标识符# 项目名 包名 模块名# 变量名 函数名 类名# 1:字母 下划线 数字组成 命名的时候不能以数字开头# 2:见名知 ...

  6. Redis应用场景说明与部署

    Redis简介 REmote DIctionary Server(Redis)是一个基于key-value键值对的持久化数据库存储系统.redis和大名鼎鼎的memcached缓存服务很像,但是red ...

  7. python摸爬滚打之day26----网络编程之socket

    1.网络通信原理 互联网的本质就是一系列的网络协议, 统称为互联网协议. 互联网协议的功能:定义计算机如何接入internet,以及接入internet的计算机通信的标准. 互联网协议按照功能不同分为 ...

  8. CNPM 安装 for angularjs

    npm config set proxy=http://127.0.0.1:8087npm config delete proxynpm config set registry=http://regi ...

  9. 【转载】MDK环境下让STM32用上FreeRTOS v8.1.2和FreeRTOS+Trace v2.6.0全过程

    [转载]https://www.amobbs.com/thread-5601460-1-2.html?_dsign=6a59067b   本人选择使用FreeRTOS的最大原因就是想使用FreeRTO ...

  10. ARGB与RGB、RGBA的区别

    ARGB 是一种色彩模式,也就是RGB色彩模式附加上Alpha(透明度)通道,常见于32位位图的存储结构. RGB 色彩模式是工业界的一种颜色标准,是通过对红(R).绿(G).蓝(B)三个颜色通道的变 ...