Is there a helper method for parsing an appSettings XML application?

By appSettings-like, I mean like this:

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

The result is a collection of key values ​​that I can get, for example:

string v = config["myKey"];

but it is not necessarily located in app.config, so I have a string or XmlNode.

The NameValueFileSectionHandler.Create method can obviously do the job, but two objects are required for input: the object's parent, the configContext object, in addition to the xml node, and I don't know what to pass to them.

+3
source share
4 answers

Parse a string in a dictionary like this,

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

You can get values ​​like this,

var item = dic["myKey"];

You can also change the values ​​in the dictionary, for example,

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))));
+5

- :

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

+1

I have not tried this, but I think the code below can give you what you want.

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

All Articles