c# - 使用 ConfigurationBuilder 读取 XML 文件时如何忽略命名空间
问题描述
我希望使用 ConfigurationBuilder 读取 XML 文件,但我不断收到“不支持 XML 命名空间”错误。有没有办法忽略命名空间?我对.net 还很陌生,所以要温柔!
我正在尝试使用 ConfigurationBuilder 从 XML 文件中检索连接字符串,以便访问云表(它是一个服务结构应用程序,并且它必须是一个 XML 文件,不幸的是) - 当我配置它时它工作正常'appsetting.json' 文件,但由于其他人设置部署配置的方式,这需要更改。
XML 遵循通常的模式,例如:
<?xml version="1.0" encoding="utf-8" ?>
<Settings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2011/01/fabric">
....ETC。
我正在使用的代码如下所示:
string path = Path.Combine(FabricRuntime.GetActivationContext().GetConfigurationPackageObject("Config").Path);
IConfiguration cloudTableConfig2 = new ConfigurationBuilder()
.SetBasePath(path)
.AddXmlFile("Settings.xml", optional: true, reloadOnChange: true)
.Build();
'GetConfigurationPackageObject' 基本上只是建立设置文件的正确路径,然后将其传递给配置生成器。
我希望它类似于 appsettings.json,因为我可以以类似于以下方式从配置中解析所需的值:
IConfiguration cloudTableConfig = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(cloudTableConfig["RequiredAzureTable:AzureConnectionString"]);
但是,这不起作用,因为我在 ConfigurationBuilder 阶段收到以下异常:
System.FormatException: 'XML namespaces are not supported. Line 2, position 11.'
我不能真正删除命名空间,因为它是一个外部配置的文件。有没有一种简单的方法来告诉 AddXmlFile 方法忽略命名空间?还是只能通过扩展 AddXmlFile 方法才能真正做到?(或者更确切地说,在 IConfiguration 上放置一个围绕 AddXmlFile 方法的扩展方法?)
解决方案
原来我把它复杂化了。鉴于它是 Service Fabric,我只需要输入:
var azureConfig = FabricRuntime.GetActivationContext().GetConfigurationPackageObject("Config");
从那里开始,它只是一个像这样检索连接字符串的简单案例(注意:可以将它们组合成一个!为简单起见,将它们保留原样):
var azureConfigSection = azureConfig.Settings.Sections["*SomeSectionName*"];
var azureDataTableConnectionString = azureConfigSection.Parameters["*ConnectionStringNameWithinSection*"].Value;
这使我能够执行以下操作:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(azureDataTableConnectionString);
推荐阅读
- c# - 玩家与对象碰撞后如何再次重生对象?
- java - 如果数据已经存在,Android Studio SQLite 不会将数据插入数据库
- api - Cypress api 测试 graphql 查询和查询变量
- python - 如何将来自客户端的消息存储在服务器中并通过 Flask 中的某些路由进一步发送
- typescript - “字符串”类型上不存在 TypeScript React Native 属性“目标”
- android - Jetpack Compose 中的 Canvas 重构
- ruby-on-rails - 由于 MimeMagic gem 不再存在,不能再将我的所有应用程序捆绑安装在需要 Paperclip 的 Rails 上?
- python - 在类中重塑、展平或拆散多维数组
- php - 以这种方式提交表格是否安全?
- spring-boot - 如何正确配置带有注释的弹性 4J 回退客户端?