如何从app.config读取自定义XML?

我想从C#windows服务的app.config中读取自定义XML部分。

我该怎么办?

XML如下:

     

您要做的是阅读自定义配置部分 。

在我开发的项目中,我使用类似于我发现的配置。 我相信这篇文章被称为我需要的最后一个配置部分处理程序(我找不到工作链接,也许有人可以为我链接它)。

此方法将您想要做的更进一步,并实际将对象反序列化到内存中。 我只是从我的项目中复制代码,但如果您想要的只是XML,那么向后退一步应该相当简单。

首先,您需要定义一个处理配置设置的类。

 using System; using System.Configuration; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; namespace Ariel.config { class XmlSerializerSectionHandler : IConfigurationSectionHandler { #region IConfigurationSectionHandler Members public object Create(object parent, object configContext, XmlNode section) { XPathNavigator nav = section.CreateNavigator(); string typename = (string)nav.Evaluate("string(@type)"); Type t = Type.GetType(typename); XmlSerializer ser = new XmlSerializer(t); return ser.Deserialize(new XmlNodeReader(section)); } #endregion } } 

现在,假设您要加载一部分配置…超级简单,转换为您期望XML序列化的对象类型,并传递您正在寻找的部分(在本例中为SearchSettings

 try { config = (Eagle.Search.SearchSettings)ConfigurationSettings.GetConfig("SearchSettings"); } catch (System.Configuration.ConfigurationException ex) { syslog.FatalException("Loading search configuration failed, you likely have an error", ex); return; } 

现在,您只需要App.config文件即可。 我选择将我分成单独的文件(每个部分1个文件),以便更轻松地管理配置。 您可以定义一个部分,为其命名,并定义类型(无论您将上面列出的类称为什么)和程序集的名称。

App.config中:

    

现在,剩下的就是要反序列化的配置文件。 这里重要的是块匹配您的节名,您的类型是它应该反序列化的任何对象,以及程序集名称。

   4  

如果您只想要纯原始XML,那么您需要做的就是修改处理该部分的Object以返回XML或执行您需要做的任何事情。

由于不推荐使用IConfigurationSectionHandler ,我认为值得一提的是,您仍然可以通过重写ConfigurationSection.DeserializeSection而不是调用基本实现来实现纯序列化部分。

这是一个非常基本的例子,我重复使用了很多。 一个简单的配置部分,用于从内联XAML加载对象图。 (当然你可以用XmlSerializer来实现)

 using System.Configuration; using System.Xaml; using System.Xml; ... public class XamlConfigurationSection : ConfigurationSection { public static XamlConfigurationSection Get(string sectionName) { return (XamlConfigurationSection)ConfigurationManager.GetSection(sectionName); } public T Content { get; set; } protected override void DeserializeSection(XmlReader xmlReader) { xmlReader.Read(); using (var xamlReader = new XamlXmlReader(xmlReader)) Content = (T)XamlServices.Load(xamlReader); } } 

我在config.app中使用自定义xml。 文件并从中创建app.XSD。 XSD文件包含config.app文件的架构。 然后可以使用“xsd.exe”将XSD文件转换为vb类或C#类文件。 现在您要做的就是将配置文件反序列化到类中。

    
QAS