使用 C# 循环遍历配置部分以读取其元素
我有一个配置文件,例如:
<logonurls>
<othersettings>
<setting name="DefaultEnv" serializeAs="String">
<value>DEV</value>
</setting>
</othersettings>
<urls>
<setting name="DEV" serializeAs="String">
<value>http://login.dev.server.com/Logon.asmx</value>
</setting>
<setting name="IDE" serializeAs="String">
<value>http://login.ide.server.com/Logon.asmx</value>
</setting>
</urls>
<credentials>
<setting name="LoginUserId" serializeAs="String">
<value>abc</value>
</setting>
<setting name="LoginPassword" serializeAs="String">
<value>123</value>
</setting>
</credentials>
</logonurls>
如何读取配置以获取传递的键名的值。这是我编写的方法:
private static string GetKeyValue(string keyname)
{
string rtnvalue = String.Empty;
try
{
ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("logonurls");
foreach (ConfigurationSection section in sectionGroup.Sections)
{
//I want to loop through all the settings element of the section
}
}
catch (Exception e)
{
}
return rtnvalue;
}
config 是具有配置文件中的数据的配置变量。
I have a configuration file, something like:
<logonurls>
<othersettings>
<setting name="DefaultEnv" serializeAs="String">
<value>DEV</value>
</setting>
</othersettings>
<urls>
<setting name="DEV" serializeAs="String">
<value>http://login.dev.server.com/Logon.asmx</value>
</setting>
<setting name="IDE" serializeAs="String">
<value>http://login.ide.server.com/Logon.asmx</value>
</setting>
</urls>
<credentials>
<setting name="LoginUserId" serializeAs="String">
<value>abc</value>
</setting>
<setting name="LoginPassword" serializeAs="String">
<value>123</value>
</setting>
</credentials>
</logonurls>
How can I read configuration to get the value of keyname passed. Here is the method that I wrote:
private static string GetKeyValue(string keyname)
{
string rtnvalue = String.Empty;
try
{
ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("logonurls");
foreach (ConfigurationSection section in sectionGroup.Sections)
{
//I want to loop through all the settings element of the section
}
}
catch (Exception e)
{
}
return rtnvalue;
}
config is the Configuration variable that has the data from the config file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将您的配置文件加载到 XmlDocument 中,按名称获取 XmlElement(设置您要读取的值)并尝试以下代码。
如何编写单个 LINQ to XML 查询来迭代所有子元素和子元素子元素的所有属性?
Load your config file into XmlDocument, get XmlElement by name (setting value you want to read) and try following code.
How to write a single LINQ to XML query to iterate through all the child elements & all the attributes of the child elements?
将其转换为正确的 XML 并在节点内搜索:
快速说明:如果将其转换为 XML,您还可以使用 XPath 来获取值。
Convert it to proper XML and search within the nodes:
Just a quick note: if you convert it to XML, you can also use XPath to get the values.