


Sample code sharing of custom XML dynamic configuration program
Overview
1 When doing program development, we often use the following two basic modules
1> Set the basic parameters of the program, such as paging parameters, email parameters, etc.;
2> When developing based on table-driven development, some judgment logic is placed in the table data;
2 Among these two basic applications, we have the following requirements:
1> It must be managed centrally;
2> It must be configurable, that is, the parameters can be modified without restarting the system;
3> It must be easy to use.
Main functions of the program
1> Set the basic parameters of the program, such as paging parameters, email parameters, etc.;
----Automatically add configuration information in XML to the corresponding entity.
2> When developing based on table-driven development, some judgment logic is placed in the table data;
----Automatically load the Dctionary data in XML to the corresponding entity . However, this method needs to continue to be optimized. Now it only supports loading Dictionary and needs to support more complex structures.
Main code
1 First define, reference the entity in the code.
Example
public class AppSetting { public string PageSize; public string WebUrl; public Dictionary<string, string> IsPartialPayment; public Dictionary<string, string> EntityCurrency; }
2 Define the corresponding XML file. Among them, the basic configuration information of the program is configured under the AppSettings
node.
<?xml version="1.0" encoding="utf-8" ?> <settings> <DictSettings> <Dict name="AppSettings" > <add key="PageSize" value="2"></add> <add key="WebUrl" value="www.baidu.com"></add> </Dict> <Dict name="IsPartialPayment"> <add key="TTPART" value="true"></add> <add key="TT50/50" value="true"></add> </Dict> <Dict name="EntityCurrency"> <add key="China" value="CNY"></add> <add key="HQ" value="USD"></add> <add key="Default" value="USD"></add> </Dict> </DictSettings> </settings>
3 Finally, a piece of XML loading code is needed to load the XML configuration information in 2 into the entity in 1.
public static class ConfigManager { public static AppSetting AppSetting; private static string xmlPath; public static Dictionary<string, Dictionary<string, string>> DictAppSettings = new Dictionary<string, Dictionary<string, string>>(); static ConfigManager() { xmlPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "AppConfig.xml"); LoadSettings(xmlPath); } private static void LoadSettings(string path) { DictAppSettings.Clear(); //加载XML中所有的key,value,并转换成Dictionary对象 XmlNode dictRootNode = FileHelper.GetXMLNode(path, "/settings/DictSettings"); foreach (XmlNode dictType in dictRootNode.ChildNodes) { Dictionary<string, string> dict = new Dictionary<string, string>(); foreach (XmlNode dictItem in dictType.ChildNodes) { dict.Add(dictItem.Attributes["key"].Value.Trim(), dictItem.Attributes["value"].Value.Trim()); } DictAppSettings.Add(dictType.Attributes["name"].Value.Trim(), dict); } //将Dictionary 对象转换成实体的字段和对应dctionary上 var serializer = new JavaScriptSerializer(); //将AppSettings转成json string jAppSetting = serializer.Serialize(DictAppSettings["AppSettings"]); DictAppSettings.Remove("AppSettings"); //将除AppSettings中的信息转成json string jDict = serializer.Serialize(DictAppSettings); //将AppSettings和其它的Dictionary 加载到对应的实体中去。 string json = string.Format("{0},{1}", jAppSetting.Remove(jAppSetting.Length - 1), jDict.Remove(0, 1)); AppSetting = serializer.Deserialize<AppSetting>(json); //当修改文件时,重新加载XML FileHelper.CacheDependencyFile(path, CacheRemovedCallback); } private static void CacheRemovedCallback(string key, object value, CacheItemRemovedReason reason) { //此方法来自Fish.Li string xmlFilePath = (string)value; // 由于事件发生时,文件可能还没有完全关闭,所以只好让程序稍等。 System.Threading.Thread.Sleep(3000); LoadSettings(xmlFilePath); } } public static class FileHelper { public static XmlNode GetXMLNode(string path, string xPath) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(path); return xmlDoc.SelectSingleNode(xPath); } public static void CacheDependencyFile(string path, CacheItemRemovedCallback removedCallback) { CacheDependency dep = new CacheDependency(path); HttpRuntime.Cache.Insert(Guid.NewGuid().ToString(), path, dep, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, removedCallback); } }
Final effect
1 When the program is run for the first time, the corresponding configuration information is output
2 When some parameters are modified , you can get the latest information without restarting. Note that after modifying the parameters for 3 seconds, refresh the page
The above is the detailed content of Sample code sharing of custom XML dynamic configuration program. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



An avatar on Netflix is a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

A Venn diagram is a diagram used to represent relationships between sets. To create a Venn diagram we will use matplotlib. Matplotlib is a commonly used data visualization library in Python for creating interactive charts and graphs. It is also used to create interactive images and charts. Matplotlib provides many functions to customize charts and graphs. In this tutorial, we will illustrate three examples to customize Venn diagrams. The Chinese translation of Example is: Example This is a simple example of creating the intersection of two Venn diagrams; first, we imported the necessary libraries and imported venns. Then we create the dataset as a Python set, after that we use the "venn2()" function to create

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.
