c# - 从 xml 文件中获取参数数组

标签 c#

我有以下 app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <xx>
      <add key="x" value="1.1.1.1" />
      <add key="y" value="1.1.1.1" />
      <add key="z" value="1.1.1.1" />
      <add key="w" value="6" />
    </xx>

    <yy>
      <add key="Wireshark" value="1" /> 
    </yy>

    <zz>
      <add key="Firmware1" value="C:\Users\Desktop\Download.txt/>
      <add key="Firmware2" value="C:\Users\Desktop\Download.txt" />
    </zz>

</configuration>

我怎样才能得到一个包含 x、y 和 w 的数组。我需要应用程序设置吗?这个 xml 是否有效?

最佳答案

首先需要在配置文件中为每个自定义section写一个自定义类;另一种选择是使用其中一种内置类型。

例如;

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="Default" type="System.Configuration.NameValueSectionHandler" />
        <section name="Maestro" type="System.Configuration.NameValueSectionHandler" />
        <section name="Drive" type="System.Configuration.NameValueSectionHandler" />
    </configSections>
    <Default>
      <add key="gmasIP" value="192.168.2.3" />
      <add key="hostIP" value="192.168.2.2" />
      <add key="GatewayIP" value="192.168.2.4" />
      <add key="relayCOM" value="6" />
    </Default>

    <Maestro>
      <add key="Wireshark" value="1" /> 
    </Maestro>

    <Drive>
      <add key="FirmwarePath" value="C:\Users\rinat\Desktop\Download.txt/>
      <add key="FirmwarePalPath" value="C:\Users\rinat\Desktop\Download.txt" />
    </Drive>

</configuration>

如果你想获取数组形式的值:

    var defaultItems= ConfigurationManager.GetSection("Default") as NameValueCollection;
    List<string> temp = new List<string>();

if (defaultItems!= null)
{
    foreach (var key in defaultItems.AllKeys)
    {
        string val= defaultItems.GetValues(key).FirstOrDefault();
        temp.Add(val);
    }
}

    string[] arr = temp.ToArray();

关于c# - 从 xml 文件中获取参数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34850939/

相关文章:

c# - 如何将多个数据集导出到 Excel 工作表

c# - 泛型类装饰器的copy方法如何实现?

c# - 在构造函数中或在类的顶部创建一个对象

c# - 动态地向现有对象添加属性

c# - .NET:Windows 窗体/控件性能

c# - 为什么在此示例中再次引用事件处理程序?

c# - 在子类的构造函数中调用基构造函数

c# - 使用 NSubstitute 模拟 Web 服务时出错

c# - Html.BeginForm 路由到 Web Api

c# - Entity Framework 通配符和 Linq