我正在尝试读取我的应用程序中的配置。
考虑下面的代码.我在内存中加载了一个XML,它包含3个不同的节点。我只能获得没有Name属性的节点的值。
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>();和Node类
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; }
}配置有3个节点,node1包含属性Name,我正在尝试使用Node1读取它。
configurationRoot.GetSection("node1").Get<Node1>()不填充值。
node2不包含属性Name,我正在尝试使用Node2读取它。
configurationRoot.GetSection("node2").Get<Node2>()按预期填充值。
最后,node3确实包含属性Name,但我试图使用Node2读取它(这并不关心名称)。
configurationRoot.GetSection("node3").Get<Node2>()也不填充任何值。
如何读取包含Name属性的节点。
发布于 2022-09-01 20:16:57
GitHub上的源代码显示,Name属性得到了特殊处理。
// The special attribute "Name" only contributes to prefix
// This method retrieves the Name of the element, if the attribute is present简而言之,name属性的值包含在(节/项)键中。
要检索node1,需要调用
var node1 = configurationRoot.GetSection("node1:something").Get<Node1>();对于node3,这是
var node3 = configurationRoot.GetSection("node3:ignored").Get<Node2>();VisualStudioforconfigurationRoot中的调试可视化程序显示了这些键。

文档解释了这个Name属性的概念,并展示了有关何时以及如何使用的一些示例。
在.NET 5和更早版本中,添加name属性以区分使用相同元素名称的重复元素。在.NET 6和更高版本中,自动索引重复元素。
https://stackoverflow.com/questions/73570692
复制相似问题