是否有一个助手方法来解析类似xml的appSettings

本文关键字:xml appSettings 有一个 方法 是否 | 更新日期: 2023-09-27 17:58:15

我指的是这样的appSettings,

<appSettings>
    <add key="myKey" value="myValue" />
</appsettings>

结果是我可以访问的键值集合,如:

string v = config["myKey"];

但它不一定位于app.config中,所以我有一个字符串或XmlNode。

Create方法显然可以完成这项工作,但除了一个xml节点外,输入还需要两个对象,Object parent,Object configContext,我不知道该传递给它们什么。

是否有一个助手方法来解析类似xml的appSettings

将字符串解析为这样的字典,

var xml = XElement.Parse("<appSettings><add key='"myKey'" value='"myValue'" /></appSettings>");
var dic = xml.Descendants("add").ToDictionary(x => x.Attribute("key").Value, x => x.Attribute("value").Value);

你可以得到这样的值,

var item = dic["myKey"];

你也可以像这样修改字典中的值,

dic["myKey"] = "new val";

您可以使用以下代码将修改后的字典转换回XElement

var newXml = new XElement("appSettings", dic.Select(d => new XElement("add", new XAttribute("key", d.Key), new XAttribute("value", d.Value))));

您可以这样做:

Hashtable htResource = new Hashtable();
    XmlDocument document = new XmlDocument();
    document.LoadXml(XmlString);
    foreach (XmlNode node in document.SelectSingleNode("appSettings"))
    {
        if ((node.NodeType != XmlNodeType.Comment) && !htResource.Contains(node.Attributes["name"].Value))
            {
                htResource[node.Attributes["name"].Value] = node.Attributes["value"].Value;
            }
    }

然后您可以使用访问值

string myValue = htResource["SettingName"].ToString();

希望能有所帮助,

Dave

它并不是一个真正的"助手",但该框架包含了被称为配置API的东西。这在配置文件中工作,并将配置XML转换为类。点击此处查看更多详细信息:

http://msdn.microsoft.com/en-us/library/ms178688(v=VS.80).aspxhttp://msdn.microsoft.com/en-us/library/2tw134k3.aspx

这一直是我使用的样本(因为我永远记不清它的确切结构):

http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx

http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx#

还有一个与VS集成的设计器:

http://csd.codeplex.com/

在谷歌上搜索"C#自定义配置部分"也会为您带来很多结果。

我还没有尝试过,但我认为下面的代码可能会满足您的需求。

System.Configuration.ConfigurationFileMap fileMap = new System.Configuration.ConfigurationFileMap(yourConfigFileLocation);
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
        var setting = configuration.AppSettings["settingName"];