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.
Related
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
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.
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");
I have some problem with getting config info, how to get isUpdatable value for some value test1 or test2, or test3 if paramiter will get outside.
I have this sample in config.
<configSections>
<sectionGroup name ="UpdateSettings">
<section name="test1" type="System.Configuration.NameValueSectionHandler"/>
<section name="test2" type="System.Configuration.NameValueSectionHandler"/>
<section name="test3" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
<UpdateSettings>
<test1>
<add key="isUpdatable" value="0"/> <!-- get from service - 1, get from config - 0,-->
</test1>
<test2>
<add key="isUpdatable" value="1"/>
</test2>
<test3>
<add key="isUpdatable" value="1"/>
</test3>
</UpdateSettings>
And this peace of C# code
name = "test1";
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSectionGroup UpdateSettings = config.GetSectionGroup("UpdateSettings");
/* this is Connect beetwen selection group and selection, but how?*/
NameValueCollection sectionSettings = ConfigurationManager.GetSection(name) as NameValueCollection;
var value = sectionSettings["isUpdatable"];
You were very close, you have array of values so sectionSettings[0] will get you first one and sectionSettings[1] second one and so on.
name = "test1";
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSectionGroup UpdateSettings = config.GetSectionGroup("UpdateSettings");
NameValueCollection sectionSettings = ConfigurationManager.GetSection(name) as NameValueCollection;
var value = sectionSettings[0]["isUpdatable"];
suppose I have the following XML:
<appSettings>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
<add key="key3" value="value3" />
<add key="key4" value="value4" />
</appSettings>
and I would like to transform it to an object like:
AppSettings["key1"] = "value1";
AppSettings["key2"] = "value2";
AppSettings["key3"] = "value3";
and so forth …
I've looked it up on the internet and haven't found yet something useful. Can someone help me out on this ?
Easy.
var xd = XDocument.Parse(xml);
var AppSettings = xd.Root.Elements("add")
.ToDictionary(
xe => xe.Attribute("key").Value,
xe => xe.Attribute("value").Value);
You could do this with LINQ quite easily:
XElement appSettings = (...); // Parse your XML and get the root Element.
var dict = appSettings.Elements().ToDictionary(el => el.Attribute("key"), el => el.Attribute("value"));
var xml = XDocument.Parse("<appSettings><add key=\"key1\" value=\"value1\" /> <add key=\"key2\" value=\"value2\" /> <add key=\"key3\" value=\"value3\" /> <add key=\"key4\" value=\"value4\" /> </appSettings>");
xml.Elements().First().Elements()
.Select (x => new { key = x.Attribute("key").Value, value = x.Attribute("value").Value })
.ToDictionary(e => e.key, e => e.value).Dump();