Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a helper method to parse an appSettings-like xml?

By appSettings-like I mean like this,

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

The result is a key-value collection that I can access like:

string v = config["myKey"];

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

NameValueFileSectionHandler.Create method apparently can do the job, but the input needs two objects, Object parent, Object configContext, in addition to a xml node, and I don't know what to pass to them.

like image 770
Louis Rhys Avatar asked Jun 03 '11 09:06

Louis Rhys


People also ask

What is ConfigurationManager?

Configuration Manager is a step-by-step user interface in Google Cloud Directory Sync (GCDS). You use Configuration Manager to create, test, and run a synchronization.

How does app config work?

App. Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.

What is AppSettings in web config?

The <appSettings> element of a web. config file is a place to store connection strings, server names, file paths, and other miscellaneous settings needed by an application to perform work.


2 Answers

Parse a string to 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 the values like this,

var item = dic["myKey"];

You can also modify the values in the dictionary like this,

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

And you can convert the modified dictionary back to a XElement using this code,

var newXml = new XElement("appSettings", dic.Select(d => new XElement("add", new XAttribute("key", d.Key), new XAttribute("value", d.Value))));
like image 178
Andrej Slivko Avatar answered Oct 17 '22 12:10

Andrej Slivko


You could do something like this :

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

Then you can access the values using:

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

Hope that helps,

Dave

like image 20
Dave Long Avatar answered Oct 17 '22 14:10

Dave Long