Get "Key" attribute in XML config file - c#

I have an XML file with a structure and trying to get value from "Key" and "Value":
<appSettings>
<add key="Url" value=" http://book.jetstar.com/"/>
<!--Id's or Xpath-->
<add key="Origin" value="somevalue"/>
<add key="Destination" value="somevalue"/>
<add key="Adult" value ="somevalue" />
<add key="somevalue"/>
<!--Controls-->
<add key="OriginCtrl" value=" Input"/>
<!--Textbox-->
<add key="DestinationCtrl" value=" Input"/>
<add key="AdultCtrl" value=" Select"/>
<add key="SearchFlightsCtrl " value=" Button"/>
</appSettings>
I am trying to create a loop that loops through the XML and get value of these "key" and "value". The code I am writing is
XmlDocument xmlDoc = new XmlDocument();
XmlNodeList xmlnodelist;
string keyname = "";
string keyvalue = "";
xmlDoc.Load(filename);
xmlnodelist = xmlDoc.SelectNodes("appSettings");
foreach (XmlNode nodes in xmlnodelist)
{
keyname = nodes.Attributes.GetNamedItem("key").Value;
keyvalue = nodes.Attributes.GetNamedItem("value").Value;
}
The error with "object not set to an instance" rises when i try to run this piece of code. I wonder if there is errors in the code where getting the Value. Any advices would be appreciated.

Since you want to get appSettings childs you should be using
xmlDoc.SelectNodes("appSettings/add");

Related

Select node based on attribute value LINQ to xml

I want to select xml node based on attribute. I'm very new to how linq to xml works, and can't write proper query. How can I fix it?
My XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Enable0" value="true" />
<!-- dumb comment -->
<add key="Enable1" value="false" />
<!-- dumb comment1-->
<add key="Enable2" value="true" />
<add key="Enable3" value="false" />
<!-- dumb comment2 -->
<add key="Enable4" value="true" />
</appSettings>
<asdf>
<a key="b"></a>
<a key="c"></a>
<a key="d"></a>
</asdf>
</configuration>
My attempt:
private string GetAttribute(string name)
{
//???
var query = from node in deafultElement.Elements("add")
where node.Attribute("key").Value == name
select node.Attribute("value").value;
return query.toString();
//currently returns "System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]"
}
You can also use linq methods' syntax to reach the same result.
string value = defaultElement.Elements("add")
.FirstOrDefault(n => n.Attribute("key").Value == name)
.Attribute("value").Value;
var query = (from node in deafultElement.Elements("add")
where node.Attribute("key").Value == name
select node.Attribute("value").Value).FirstOrDefault();
return query

XmlNodeList.SelectSingleNode() returning null for different XML formats

I have an XML like:
<configuration>
<connectionStrings>
<add name="name1" value="value1">
<add name="name2" value="value2">
</connectionStrings>
<configuration>
In this i get
XmlNodeList nodeList = doc.GetElementsByTagName("connectionStrings");
foreach(XmlNode xn in nodeList)
{
var anode = xn.SelectSingleNode("add");
}
Here "var anode" is returning me right values of "name" attribute.
But when my xml is like:
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<connectionStrings>
<add name="name1" value="value1">
<add name="name2" value="value2">
</connectionStrings>
<configuration>
I get anode as null.
Please help.
The following code works for me:
var xElement = XElement.Load("Sample.xml");
var elements = xElement.Elements().Elements();
foreach (var element in elements)
{
var name = element.Attribute("value").Value;
}
Please try this.
Note: The Sample.xml contains:
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<connectionStrings>
<add name="name1" value="value1"/>
<add name="name2" value="value2"/>
</connectionStrings>
</configuration>
The xml file which you posted didnot close properly. Above xml is properly formatted.

Get array of parameters from xml file

i have the following app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<xx>
<add key="x" value="1.1.1.1" />
<add key="y" value="1.1.1.1" />
<add key="z" value="1.1.1.1" />
<add key="w" value="6" />
</xx>
<yy>
<add key="Wireshark" value="1" />
</yy>
<zz>
<add key="Firmware1" value="C:\Users\Desktop\Download.txt/>
<add key="Firmware2" value="C:\Users\Desktop\Download.txt" />
</zz>
</configuration>
how can i have an array for x, y and w. should i need appsettings ? does this xml is valid?
First, you need to write a custom class for each custom section in the configuration file; another option is to use one of the built-in types.
For example;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Default" type="System.Configuration.NameValueSectionHandler" />
<section name="Maestro" type="System.Configuration.NameValueSectionHandler" />
<section name="Drive" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<Default>
<add key="gmasIP" value="192.168.2.3" />
<add key="hostIP" value="192.168.2.2" />
<add key="GatewayIP" value="192.168.2.4" />
<add key="relayCOM" value="6" />
</Default>
<Maestro>
<add key="Wireshark" value="1" />
</Maestro>
<Drive>
<add key="FirmwarePath" value="C:\Users\rinat\Desktop\Download.txt/>
<add key="FirmwarePalPath" value="C:\Users\rinat\Desktop\Download.txt" />
</Drive>
</configuration>
If you want to get the values as an array:
var defaultItems= ConfigurationManager.GetSection("Default") as NameValueCollection;
List<string> temp = new List<string>();
if (defaultItems!= null)
{
foreach (var key in defaultItems.AllKeys)
{
string val= defaultItems.GetValues(key).FirstOrDefault();
temp.Add(val);
}
}
string[] arr = temp.ToArray();
This is the simple snippet taking descendants values from XML,
string[] arr1 = XDocument.Load(#"C:\xxx.xml").Descendants("Default")
.Select(element => element.Value).ToArray();
string[] arr2 = XDocument.Load(#"C:\xxx.xml").Descendants("Maestro")
.Select(element => element.Value).ToArray();
string[] arr3 = XDocument.Load(#"C:\xxx.xml").Descendants("Drive")
.Select(element => element.Value).ToArray();
use this code,.
You could read custom section of config files as below,
var defaultSettings = ConfigurationManager.GetSection("Default") as NameValueCollection; //You can replace Default with any other node name like Maestro, Drive
string hostIp = defaultSettings["hostIP"].ToString(); //you can access any of the key value under Default node in your xml config now.
Note that you may have to add a reference to System.Configuration from Framework.

Read all key values from app.config c#

Hi i have the following app.config file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="DayTime" value="08-20" />
<add key="NightTime" value="20-08" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
<add key="GridMode" value="1"/>
</appSettings>
I need to read all the keys at one shot and store it some where like Dictionary.
I have tried following code but give me null value
with exception Cannot convert Keyvalueinternalcollection to hashtable
var section = ConfigurationManager.GetSection("appSettings") as Hashtable;
How to read all keys with their values ?
Hashtable version.
Hashtable table = new Hashtable((from key in System.Configuration.ConfigurationManager.AppSettings.Keys.Cast<string>()
let value= System.Configuration.ConfigurationManager.AppSettings[key]
select new { key, value }).ToDictionary(x => x.key, x => x.value));
Comment to other answers
System.Configuration.ConfigurationManager.AppSettings is predefined 'appSettings' section, use it.
Do not cast to Hashtable but to IEnumerable instead:
var section = ConfigurationManager.GetSection("appSettings");
foreach (var kvp in section as IEnumerable)
{
//TODO
}
I think you can do something like this:
var loc=(NameValueCollection)ConfigurationSettings.GetSection("appSettings");
var dic=new Dictionary<string,string>();
foreach (var element in loc.AllKeys)
{
dic.Add(element, loc[k]);
}
var section = ConfigurationManager.GetSection("appSettings")
should suffice.

How to fetch key based on values from app.config file?

I have an app.config file like this:-
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="botLogs" value="d:\TFS Projects-BotLogs/"/>
<add key="botfolder" value="C:\BOTSCONFIG"/>
</appSettings>
<connectionStrings>
<add connectionString="Server=1.1.1.1;Database=BGAppCrawling;UID=sa;Password=something;" name="VGDB"/>
<add connectionString="Server=1.1.1.1;Database=BGMappingStaging;UID=sa;Password=something;" name="VGDBMapping"/>
</connectionStrings>
</configuration>
Now I can fetch values based on keys in appSettings section like this:-
string filePath = ConfigurationSettings.AppSettings["botLogs"].ToString();
But what is the way if I want to fetch key based on values from appSetting section ?
foreach(string key in System.Configuration.ConfigurationSettings.AppSettings)
{
var key = key.ToString();
var value = ConfigurationSettings.AppSettings[key.ToString()];
//Do something here
}
or
var settings = System.Web.Configuration.ConfigurationSettings.AppSettings;
var value = from string k in settings.Keys
where k.StartsWith("MyValue")
select settings[k];
foreach (string key in Configuration.AppSettings.Settings.AllKeys)
{
string value = appSettings.Settings[key].Value;
if (value.Equals(myValue))
{
Console.WriteLine("Found Key: " + key);
break;
}
}
i would say that you should replace your keys with values and the values with the keys,
<add key="d:\TFS Projects-BotLogs/" value="botLogs"/>
<add key="C:\BOTSCONFIG" value="botfolder"/>
thanks
rakesh
You can try following GetEnumerator method based code :
NameValueCollection values = ConfigurationManager.AppSettings;
Iterate(values);
public void Iterate(NameValueCollection myCollection)
{
IEnumerator myEnumerator = myCollection.GetEnumerator();
Console.WriteLine("KEY VALUE");
foreach (String item in myCollection.AllKeys)
Console.WriteLine(" {0,-10} {1}", item, myCollection[item]);
Console.WriteLine();
}

Categories

Resources