I am trying to read a configuration in my application.
Consider the code below...I load an XML in memory and it contains 3 different nodes.
I can only get the value of the node with no Name attribute
const string content = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<node1 Name=""something"" Foo=""Bar"" />
<node2 NoName=""something"" Foo=""Bar"" />
<node3 Name=""ignored"" NoName=""something"" Foo=""Bar"" />
</configuration>";
var doc = new XmlDocument();
doc.LoadXml(content);
using var stream = new MemoryStream();
doc.Save(stream);
stream.Position = 0;
var configurationRoot = new ConfigurationBuilder()
.AddXmlStream(stream)
.Build();
var node1 = configurationRoot.GetSection("node1").Get<Node1>();
var node2 = configurationRoot.GetSection("node2").Get<Node2>();
var node3 = configurationRoot.GetSection("node3").Get<Node2>();
And the Node classes
private class Node1
{
public string Name { get; set; }
public string Foo { get; set; }
}
private class Node2
{
public string NoName { get; set; }
public string Foo { get; set; }
}
The configuration has 3 nodes,
node1 contains the attribute Name and I am trying to read it using Node1
configurationRoot.GetSection("node1").Get<Node1>() does not populate the values.
node2 does not contain the attribute Name and I am trying to read it using Node2
configurationRoot.GetSection("node2").Get<Node2>() populate the values as expected.
Finally, node3 does contain the attribute Name but I am trying to read it using Node2, (that does not care about the name).
configurationRoot.GetSection("node3").Get<Node2>() also does not populate any of the values.
How can I read a node that contains a Name attribute.
The source code on GitHub shows that the
Nameattribute gets a special treatment.In short, the value of the
nameattribute is being included in the (section/item) key.To retrieve
node1you need to callFor
node3that isThe debug visualizer in Visual Studio for
configurationRootshows these keys.The documentation explains the concept of this
Nameattribute and shows some examples about when and how to use.