【问题标题】:Is there a standard way to store arbitary settings in an XML file for use by .net?是否有一种标准方法可以将任意设置存储在 XML 文件中以供 .net 使用?
【发布时间】:2011-01-17 16:03:49
【问题描述】:

理想情况下,我会使用与 app.config 基本结构相同的文件并拉取设置购买,只要我可以为设置获取任何类型的“路径”XML 存储就可以了。

理想情况下是这样的:

<Root>
 <ApplicationSettings>
  <Setting key="SomeKey", value="SomeValue"/>
 </ApplicationSettings>
</Root>

我会这样称呼:

Settings.Get("ApplicationSettings.SomeKey");

并获得“SomeValue”作为 lresult。

任何人都知道有什么简单的标准可以做到这一点吗?

【问题讨论】:

    标签: .net xml settings


    【解决方案1】:

    是的。

    很久以前,Craig Andera 描述了the last configuration handler you'll ever need。它使用 app.config 来提供配置。您可以修改它以从其他地方获取配置。

    编辑
    上面的链接好像被移动了
    http://sites.google.com/site/craigandera/craigs-stuff/clr-workings/the-last-configuration-section-handler-i-ll-ever-need

    【讨论】:

    【解决方案2】:

    您可以构建一个提取值的函数。我已经这样做了

     Public Class Settings
         Public Function GetSetting(Byval SettingsKey As String) As String
    
            Dim xDoc As New XmlDocument
            xDoc.Load("app.config")
            Dim xNode As XmlNode
            xNode = xDoc.SelectSingleNode(("Settings/setting[@item='" & SettingsKey & "']"))
            If xNode Is Nothing Then
                Return String.Empty
            Else
                Return xNode.Attributes("value").Value
            End If
            xDoc = Nothing
    
        End Sub
    End Class
    

    然后这样称呼它

    Settings.GetSetting("MyArbitraryKey")
    

    【讨论】:

      【解决方案3】:

      标准是使用app.config/web.config。

      我不知道您从哪里听说过更改它不是最佳做法 - 我认为有人试图愚弄您。

      【讨论】:

        【解决方案4】:

        我不确定我是否理解这个问题,因为您似乎对 App.Config 文件很熟悉...有一种方法与您发布的内容非常相似。为您的项目创建一个 App.Config 文件,并将以下代码放入其中:

        <?xml version="1.0" encoding="utf-8" ?>
        <configuration>
            <appSettings>
                <add key="Key1" value="Value1" />
                <add key="Key2" value="Value2" />
            </appSettings>
        </configuration>
        

        然后你可以在你的代码中使用:

        string key1= ConfigurationSettings.AppSettings["Key1"];
        

        【讨论】:

        • 但我不想使用文字 App.Config 认为允许它更改是违反最佳实践的。
        • @firoso - 我想我错过了关于你的问题的一些东西......你需要使用 App.Config 文件做什么? App.Config 文件是在 .NET 项目中保存配置设置的标准方式,供整个项目使用。
        • 你是什么意思允许它改变是违反最佳实践的?我假设您的意思是编辑 web.config 是违反最佳做法的,但是您可以在 web.config 中保留静态值并在外部 app.config 中引用其他值(请参阅weblogs.asp.net/pwilson/archive/2003/04/09/5261.aspx)我在您的问题中看到的唯一值正如所发布的,能够添加许多不同的文件和/或配置部分。
        • 他说的是“与 app.config 相同的基本结构”,不一定是 app.config。
        • ConfigurationSettings.AppSettings 如果设置位于 app.config/web.config、包含的配置、machine.config 机器的 web.config 或其他任何内容中,则有效。
        猜你喜欢
        • 1970-01-01
        • 2021-03-19
        • 1970-01-01
        • 2021-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-11
        • 2011-08-13
        相关资源
        最近更新 更多