从XML加载自定义部分

时间:2010-06-22 07:53:06

标签: c# .net configuration

我想为我正在开发的用于访问配置的应用程序添加一项功能。 默认情况下,应用程序将在app.config文件中搜索我提供的部分。 如果在app.config中找不到它,它将在数据库中查找具有以下列的特定表:

SectionType, SectionName, SectionData

SectionData列是一个文本列,其中包含XML格式的部分数据(与app.config文件中的部分完全相同) 我可以获取SectionData内容,但我无法将其加载到自定义ConfigurationSection中,就像我在app.config文件中所做的那样:

var mySectionObj = ConfigurationManager.GetSection("myCustomSection");

为了简化,我的问题实际上是如何从XML字符串而不是配置文件中获取自定义ConfigurationSection对象?

2 个答案:

答案 0 :(得分:0)

您可以将字符串加载到XDocument对象中并从那里读取它。

答案 1 :(得分:-1)

我认为这根本不可能 - 使用.NET的ConfigurationManager类,据我所知,甚至不可能打开你想要的任何文件 - 你只能使用app.config文件。从文件以外的其他来源读取配置数据?不行。

您可以自己分析XML-String(使用“XmlDocument.LoadXml(string)”),也可以修改app.config文件并再次阅读。

问题是:为什么配置文件中没有CustomSection?这应该被视为错误(然后更新配置文件将是最好的,我认为)。或者是否打算,某些配置文件没有CustomSection?

如果设置可能在XML文件中,则将设置添加到文件中将是这样的:

XmlDocument appconfig = new XmlDocument();

appconfig.Load("[config_filename]");
XmlNode root = appconfig.DocumentElement;

XmlDocument mysection = new XmlDocument();
mysection.LoadXml([SectionData]);
XmlNode customSection = mysection.DocumentElement;

XmlNode tempNode = appconfig.ImportNode(customSection, true);
root.AppendChild(tempNode);

appconfig.Save("[config_filename]");

...

var mySectionObj = ConfigurationManager.GetSection("myCustomSection");

如果这不可取,我会看到两种可能性: 第一: 尽管如此:更改.config文件,读取它,然后将其更改回来。 (或复制文件,更改原件,读取,删除,将副本重命名为原始名称)。 这种方式并不好,在我看来,它有点不纯,但它有一些很大的优点:它很有用,很容易维护。

第二: 将XML字符串加载到XmlDocument:XmlDocument.LoadXml(xmlstring) 然后使用“doc.ChildNodes”或“doc.SelectNodes(xpath)”或“doc.SelectSingleNode(xpath)”分析xmldocument。 这将是更多的工作,尤其是因为您必须维护例程以将配置设置添加到项目中,因此我不建议使用此方法。强烈不推荐。