[英]Get array of parameters from xml file
i have the following app.config: 我有以下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>
how can i have an array for x, y and w. 我怎么能有一个x,y和w数组。 should i need appsettings ?
我应该需要appsettings吗? does this xml is valid?
这个xml有效吗?
This is the simple snippet taking descendants values from XML, 这是从XML中获取后代值的简单代码段,
string[] arr1 = XDocument.Load(@"C:\xxx.xml").Descendants("Default")
.Select(element => element.Value).ToArray();
string[] arr2 = XDocument.Load(@"C:\xxx.xml").Descendants("Maestro")
.Select(element => element.Value).ToArray();
string[] arr3 = XDocument.Load(@"C:\xxx.xml").Descendants("Drive")
.Select(element => element.Value).ToArray();
use this code,. 使用此代码。
First, you need to write a custom class for each custom section in the configuration file; 首先,您需要为配置文件中的每个自定义部分编写自定义类; another option is to use one of the built-in types.
另一种选择是使用其中一种内置类型。
For example; 例如;
<?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>
If you want to get the values as an array: 如果要将值作为数组获取:
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();
You could read custom section of config files as below, 您可以阅读配置文件的自定义部分,如下所示,
var defaultSettings = ConfigurationManager.GetSection("Default") as NameValueCollection; //You can replace Default with any other node name like Maestro, Drive
string hostIp = defaultSettings["hostIP"].ToString(); //you can access any of the key value under Default node in your xml config now.
Note that you may have to add a reference to System.Configuration from Framework. 请注意,您可能必须从Framework添加对System.Configuration的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.