如何在C#中以XML格式读取web.config部分? [英] How to read web.config section as XML in C#?
问题描述
以下是复制的示例:
我想从app.config中阅读以下自定义部分:
I want to read following custom section from app.config:
<StartupFolders>
<Folders name="a">
<add folderType="Inst" path="c:\foo" />
<add folderType="Prof" path="C:\foo1" />
</Folders>
<Folders name="b">
<add folderType="Inst" path="c:\foo" />
<add folderType="Prof" path="C:\foo1" />
</Folders>
</StartupFolders>
这也是我的情况.但是,我不想创建用于处理值的自定义类,在web.config中定义此类,然后最终使用它.它很重,可以满足我的需求.
And this is my case too. However, I don't want to create custom class for handling values, defining this class in web.config, and then finally using it. It is heavy-weight for my needs.
相反,我想做一些非常简单的事情-以XML格式检索节.然后,我可以使用常规的Linq.Xml对其进行解析.这样,我不需要为每个部分创建新的类,也不需要声明它们.就我的目的而言,一方面就足够了,而另一方面却极少(我做了一次,嵌套部分的键值映射器). IE.完美.
Instead I would like to do something very simple -- retrieve a section as XML. Then I could use regular Linq.Xml to parse it. This way, I don't need to create new classes per each section, I don't need to declare them. For my purpose it is sufficient on one hand, and minimal at the other (I do it once, key-value mapper for nested sections). I.e. perfect.
唯一缺少的部分是(我的问题)-如何将web.config部分作为XML获取? 请注意以下部分:
The only missing piece is (my question) -- how to get a web.config section as XML? Note about the section:
- 无法对其进行编码,因为必须手动对其进行编辑
- 由于相同的原因而无法序列化
因此,我不是要寻找一种解决方法来压缩整个部分作为appSettings中的值,而是要寻找一种方法来获取适当的XML段落.
So I am not looking for a workaround how to squeeze entire section as value in appSettings, but I am really looking for a method to get proper section as XML.
我想从ConfigManager(!)中获取它,因为这样一来,我不必处理要读取哪个web.config的问题,依此类推.比手动模仿web.config优先级的机会少.
I would like to get it from ConfigManager (!), because this way I don't have to deal with resolving which web.config should I read, etc. I.e. less chance to make mistake than mimicing web.config precedence manually.
请原谅我提醒您,但请避免使用答案",您不应这样做,请在每个部分中使用自定义类,以此类推.我已经考虑过并选择反对.
推荐答案
我认为您必须手动执行并将Web配置加载到内存中.
I think you either have to do it manually and load the Web config into memory:
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Web.config"));
否则,您将需要创建要避免的自定义配置部分.
Or you will need to create the custom configuration sections you want to avoid.
这篇关于如何在C#中以XML格式读取web.config部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!