C# 有没有一种方法可以基于任意xml获取System.Configuration.Configuration实例?

C# 有没有一种方法可以基于任意xml获取System.Configuration.Configuration实例?,c#,.net,testing,configuration,configurationmanager,C#,.net,Testing,Configuration,Configurationmanager,我正在尝试对我编写的自定义配置部分进行单元测试,我希望将一些任意配置XML加载到for each test中(而不是将测试配置XML放入Tests.dll.config文件中)。也就是说,我希望执行以下操作: Configuration testConfig = new Configuration("<?xml version=\"1.0\"?><configuration>...</configuration>"); MyCustomConfigSectio

我正在尝试对我编写的自定义配置部分进行单元测试,我希望将一些任意配置XML加载到for each test中(而不是将测试配置XML放入Tests.dll.config文件中)。也就是说,我希望执行以下操作:

Configuration testConfig = new Configuration("<?xml version=\"1.0\"?><configuration>...</configuration>");
MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection");
Assert.That(section != null);
Configuration testConfig=新配置(“…”);
MyCustomConfigSection=testConfig.GetSection(“MyCustomConfigSection”);
Assert.That(节!=null);

但是,它似乎只提供与EXE文件或计算机配置相关联的配置实例。有没有办法将任意XML加载到配置实例中?

看看类的成员,我会说答案可能是否定的*。我不确定您为什么要这样做,而不是创建自己的own XML配置文件


*不,不包括杂乱的反射黑客,我想你要找的是ConfigurationManager

它允许您打开使用文件路径(包装在文件中)指定的配置文件


如果另一张海报上说的是真的,并且您不希望创建一个全新的XML文件进行测试,那么我建议您将配置编辑放在测试方法本身中,然后针对新更改的配置数据运行测试。

我发现了一种方法

您需要定义一个从原始配置节继承的新类,如下所示:

public class MyXmlCustomConfigSection : MyCustomConfigSection
{
    public MyXmlCustomConfigSection (string configXml)
    {
        XmlTextReader reader = new XmlTextReader(new StringReader(configXml));
        DeserializeSection(reader);
    }
}
string configXml = "<?xml version=\"1.0\"?><configuration>...</configuration>";
MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml);

然后,您可以按如下方式实例化ConfigurationSection对象:

public class MyXmlCustomConfigSection : MyCustomConfigSection
{
    public MyXmlCustomConfigSection (string configXml)
    {
        XmlTextReader reader = new XmlTextReader(new StringReader(configXml));
        DeserializeSection(reader);
    }
}
string configXml = "<?xml version=\"1.0\"?><configuration>...</configuration>";
MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml);
string configXml=“…”;
MyCustomConfigSection config=新的MyXmlCustomConfigSection(configXml);

希望它能帮助一些人:-)

帮助他回答问题。虽然自定义Xml读取是一个很好的解决方案,但Xml片段并不正确。DeserializeSection希望xml就是这样的部分