65.9K
CodeProject 正在变化。 阅读更多。
Home

CXMLProfile - 应用程序的简单 XML 配置文件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.44/5 (6投票s)

2002 年 8 月 19 日

2分钟阅读

viewsIcon

135917

downloadIcon

1310

一个使用 XML 文件存储应用程序配置文件的 MFC 类。

引言

对于程序员来说,存储和加载应用程序的配置数据是一项非常常见的任务,并且有很多方法可以实现:将信息存储在文件中、注册表中、Windows 通用初始化文件(system.ini, win.ini 等)中……但是,信息保存和共享有了一个新的标准,那就是 XML。

Windows API 和 MFC 具有一组函数,可以极大地简化这些过程,可以从 win.ini、注册表或任何基于 Windows-INI 结构的文件中存储和检索信息。 目前,在 Visual C++ 下处理 XML 文件有点复杂,因为 Microsoft XML 服务的 COM 本质。

CXMLProfile 是一个类,它通过将标准配置输入/输出操作封装在一组非常简单的函数中,从而简化了这项工作。

使用 CXMLProfile

当您实例化一个 CXMLProfile 类并调用 loadProfile 函数时,它会尝试打开 XML 文件,该文件包含构造函数的第一个参数指定的配置文件; 如果未找到,则会创建一个空白配置文件。 每次调用 saveProfile 函数时,数据都会存储在文件中。

现在,让我们看一下该类的公共声明

CXMLProfile(LPCTSTR lpszProfileName);

bool writeProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nValue);
bool writeProfileString(LPCTSTR lpszSection, 
    LPCTSTR lpszEntry, LPCTSTR lpszData);

int getProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nDefault);
LPSTR getProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, 
    LPCSTR lpszDefault, LPSTR lpBuffer, UINT nBufferSize);

bool saveProfile();
bool loadProfile();

~CXMLProfile();

函数原型是不言自明的,但我将给出一个简短的描述

  • CXMLProfile(LPCTSTR lpszProfileName)

    唯一的一个构造函数,lpszProfileName 包含配置文件名称(例如,您的应用程序名称)。

  • virtual ~CXMLProfile();

    唯一的一个析构函数; 执行类清理。

  • bool writeProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nValue);

    将整数值写入指定的节和条目。

  • bool writeProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszData);

    将字符串值写入指定的节和条目。

  • int getProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nDefault);

    从指定的节和条目检索整数值。

  • LPSTR getProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCSTR lpszDefault, LPSTR lpBuffer, UINT nBufferSize);

    从指定的节和条目检索字符串值。

  • bool saveProfile();

    将当前配置文件保存到磁盘。

  • bool loadProfile();

    从磁盘加载当前配置文件。 必须在从配置文件读取或写入之前调用它。

注释

要使用此代码,只需将 xmlprofile.hxmlprofile.cpp 包含到您的项目中,并将 comsupp.lib 添加到链接器依赖项中。

示例代码:

#include "xmlprofile.h"

int main()
{
    CXMLProfile xmlProfile("MyApplication");

    xmlProfile.loadProfile();

    // write some stuff in the profile
    xmlProfile.writeProfileString("Owner", "Name", "John");
    xmlProfile.writeProfileInt("Owner", "Age", 20);

    // now let´s retrieve it
    CHAR szName[255];

    xmlProfile.getProfileString("Owner", "Name", "None", szName, 255);
    int nAge = xmlProfile.getProfileInt("Owner", "Age", 0);

    // Warning! the destructor will not save to file any data... 
    // we have to use saveProfile()
    xmlProfile.saveProfile();
}

更新

  • 2002 年 8 月 21 日 - 现在,如果当前操作系统允许(NT/2000/XP),则使用“Documents and Settings\用户名”目录来存储配置文件。
  • 2004 年 2 月 18 日 - 现在,该类不依赖于 MFC,并且添加/改进了一些函数。
© . All rights reserved.