i'm trying to load Configuration Values from XML Files using the IConfiguration/ConfigurationBuilder (Microsoft.Extensions.Configuration). But everytime i want to get a Value, i just get null
This is one of the XML Configuration File
<Application>
<Configuration>
<Modules>
<SampleModule>
<Detection>
<ScaleFactor>1.3</ScaleFactor>
<MinNeighbors>1</MinNeighbors>
<MinSize></MinSize>
<MaxSize></MaxSize>
</Detection>
<Overlay>
<Draw>true</Draw>
<Text>Face</Text>
<TextColor>
<A>0</A>
<R>255</R>
<G>0</G>
<B>0</B>
</TextColor>
<BoxColor>
<A>0</A>
<R>255</R>
<G>0</G>
<B>0</B>
</BoxColor>
<BoxBorderSize>1.5</BoxBorderSize>
</Overlay>
<UseEvents>true</UseEvents>
</SampleModule>
</Modules>
</Configuration>
</Application>
This is a Simple NUnit Test i wrote to debug the issue
[Test]
public void TestConfigurationParsing() {
ConfigurationBuilder builder = new();
String configPath = Path.Join(Directory.GetCurrentDirectory(), "Configuration", "EyeDetection.xml");
String xmlPath = "Application:Configuration:Modules:SampleModule:Overlay:Text";
// /Application/Configuration/Modules/SampleModule/Overlay/Text
if (!File.Exists(configPath)) {
throw new FileNotFoundException($"Could not find {configPath}");
}
builder.AddXmlFile(configPath);
IConfigurationRoot config = builder.Build();
Assert.IsNotNull(config[xmlPath]);
Assert.That(config[xmlPath], Is.EqualTo("Face"));
// Assert.IsNotNull(config.GetValue<String>(xmlPath));
// Assert.That(config.GetValue<String>(xmlPath), Is.EqualTo("Face"));
}
This Failes. I Just get null
with every value. Regardless of Type (Boolean, Int32, String etc. )
Regarding the Paths:
My Application is in .
All the Configuration Files are in ./Configuration/*.xml
Is there something i'm doing wrong? I can't seem to figure it out...
The configuration system ignores the < root > element. So your xml path
var xmlPath = "Configuration:Modules:SampleModule:Overlay:Text";
and value (Microsoft.Extensions.Configuration.Binder should be installed)
var text = config.GetValue<string>(xmlPath); // "Face"
//or a full syntax
text = config.GetSection(xmlPath).Get<string>(); // "Face"