Class that can return the value of an element from xml
I need to implement some kind of solution - my c # function i use so many coded 5 digit codes. what i want is to move these hardcoded values ββinto the mapping config file (some xml) and the config will map the codes to constants that can be used in my function.
This will help update the meaning of the code without recompiling the source code.
XML will look like this:
<Codes>
<Code>
<key>code_name_1</key>
<value>value_1</value>
</Code>
...
</Codes>
OR
<Codes>
<Code key='code_name_1' value='value_1'>
<Code key='code_name_2' value='value_2'>
<Code key='code_name_3' value='value_3'>
...
</Codes>
display class:
static class codeMapping
{
const sting code1 = "code_name_1";
const sting code2 = "code_name_2";
const sting code3 = "code_name_3";
const sting code4 = "code_name_4";
...
}
where i want to get these values:
class someClass
{
...someFunction(string someCode)
{
...
if(someCode == codeMapping.code1)
...do something
var temp2 = codeMapping.code2;
...
}
}
How do I initialize the constant variables of the codeMapping class to the appropriate configuration values? Any best design concept is also accepted.
+3
source to share
1 answer
Use readonly static fields instead and initialize it inside the constructor. Hopefully this is what you are trying to achieve.
class Program
{
static void Main(string[] args)
{
var s = CodeMapping.Code1;
}
public static class CodeMapping
{
private static readonly string _code1;
private static readonly string _code2;
static CodeMapping()
{
string filePath = "code file path";
var doc = XElement.Load(filePath);
_code1 = doc.Elements().SingleOrDefault(r => r.Element("key").Value == "code_name_1").Element("value").Value;
_code2 = doc.Elements().SingleOrDefault(r => r.Element("key").Value == "code_name_2").Element("value").Value;
}
public static string Code1 { get { return _code1; }}
public static string Code2 { get { return _code2; } }
}
}
0
source to share