从Initializationstring中提取值并作为键值对返回

时间:2012-07-11 19:17:26

标签: c# .net dictionary initialization

我有一部分应用程序初始化字符串:

<Controls>
  <HtmlElement name="lnkLogIn" type="HtmlElement">
    <AttributeMatchPath matchtype="equals">
      <href>JavaScript:void(0)</href>
      <id>s_swepi_22</id>
    </AttributeMatchPath>
  </HtmlElement>
  <InputElement name="tbPassword" type="InputElement">
    <AttributeMatchPath matchtype="equals">
      <id>s_swepi_2</id>
    </AttributeMatchPath>
  </InputElement>
  <InputElement name="tbUserID" type="InputElement">
    <AttributeMatchPath matchtype="equals">
      <id>s_swepi_1</id>
    </AttributeMatchPath>
  </InputElement>
</Controls>

我想在后面的代码中做的是一个函数,它将每个控件的Inputelement名称和id作为键值对获取,并返回一个字典对象或类似的东西,我们可以从中提取键值对信息。

这基本上是为了删除ID值的硬编码....所以从init字符串中获取elementname和id并将它们存储为键值对的通用解决方案真的很棒....提前感谢:)

PS:使用C#.....

1 个答案:

答案 0 :(得分:0)

好的......做完......:)

这就是我所做的:使用system.xml.linq功能:

这是工作代码:

using System.Linq;
using System.Xml.Linq;

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    public static void Main ( )
    {
        var xDoc = XElement.Load ( "ApplicationInit.xml" );
        var appSettingsDictionary = (xDoc.Descendants("InputElement")
            .Select ( item => new 
                             { 
                                 Key = item.Attribute("name").Value,
                                 Value = item.Descendants("id").First().Value 
                             }
                    )
                ).ToDictionary ( item => item.Key, item => item.Value );
    }
}

}

相关问题