0

次のような構成ファイルがあります。

<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>

設定を読み取って、渡されたkeynameの値を取得するにはどうすればよいですか。これが私が書いた方法です:

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は、構成ファイルのデータを持つ構成変数です。

4

2 に答える 2

1

構成ファイルを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)
{
    // ...
}

単一のLINQtoXMLクエリを記述して、すべての子要素と子要素のすべての属性を反復処理するにはどうすればよいですか?

于 2011-04-15T19:22:47.733 に答える
0

それを適切な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");
于 2011-04-15T18:58:31.190 に答える