首页 > 解决方案 > 使用 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 方法的扩展方法?)

标签: c#.netxml

解决方案


原来我把它复杂化了。鉴于它是 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);

推荐阅读