C# 循环通过configration部分读取它';使用C语言创建s元素#
我有一个配置文件,类似于:C# 循环通过configration部分读取它';使用C语言创建s元素#,c#,configuration,configurationsection,C#,Configuration,Configurationsection,我有一个配置文件,类似于: <logonurls> <othersettings> <setting name="DefaultEnv" serializeAs="String"> <value>DEV</value> </setting> </othersettings> <urls> <setting name="DEV" seri
<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>
config是包含配置文件中数据的配置变量。将其转换为正确的XML并在节点内搜索:
private static string GetKeyValue(string keyname)
{
string rtnValue = String.Empty;
try
{
ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("logonurls");
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(sectionGroup);
foreach (System.Xml.XmlNode node in doc.ChildNodes)
{
// I want to loop through all the settings element of the section
Console.WriteLine(node.Value);
}
}
catch (Exception e)
{
}
return rtnValue;
}
请注意:如果将其转换为XML,还可以使用XPath获取值
System.Xml.XmlNode element = doc.SelectSingleNode("/NODE");
将配置文件加载到XmlDocument中,按名称获取XmlElement(设置要读取的值),然后尝试以下代码
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xmlfilename);
XmlElement elem = doc.GetElementByName("keyname");
var allDescendants = myElement.DescendantsAndSelf();
var allDescendantsWithAttributes = allDescendants.SelectMany(elem =>
new[] { elem }.Concat(elem.Attributes().Cast<XContainer>()));
foreach (XContainer elementOrAttribute in allDescendantsWithAttributes)
{
// ...
}
System.Xml.XmlDocument doc=new System.Xml.XmlDocument();
doc.LoadXml(xmlfilename);
XmlElement elem=doc.GetElementByName(“keyname”);
var allsubstands=myElement.substantsandself();
var allgenderantswithattributes=allsubstands.SelectMany(elem=>
新[]{elem}.Concat(elem.Attributes().Cast());
foreach(所有子代属性中的XContainer ElementAttribute)
{
// ...
}
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xmlfilename);
XmlElement elem = doc.GetElementByName("keyname");
var allDescendants = myElement.DescendantsAndSelf();
var allDescendantsWithAttributes = allDescendants.SelectMany(elem =>
new[] { elem }.Concat(elem.Attributes().Cast<XContainer>()));
foreach (XContainer elementOrAttribute in allDescendantsWithAttributes)
{
// ...
}