using namespace Poco::Util;
using namespace Poco;
// 1. 创建空的配置
AutoPtr<XMLConfiguration> cfg(new XMLConfiguration());
// 2. 设置根的名称
cfg->loadEmpty("config");
// 3. 写入配置节点
cfg->setString("appconfig", "");
cfg->setString("users[@id]", "abc");
cfg->setString("items.item[@id]", "18000");
// 4. 中文的处理。需要保存中文的时候,必须把中文编码为 utf8,POCO 的 xml 类才能解析。
cfg->setString("other[@name]", toUTF8("中文"));
// 5. 保存配置文件
cfg->save("aa.xml");
保存后,aa.xml中的内容为:
<config>
<appconfig/>
<users id="abc"/>
<items>
<item uid="18000"/>
</items>
<other name="中文"/>
</config>
// 1. 载入配置文件
AutoPtr<XMLConfiguration> cfg(new XMLConfiguration("aa.xml"));
// 2. 获取节点的值
std::string aa1 = cfg->getString("appconfig");
std::string aa2 = cfg->getString("users[@id]");
std::string aa3 = cfg->getString("items.item[@id]");
// 3. 中文的处理
std::string chinese = cfg->getString("other[@name]");
// 这时候读取出来的是 utf8 编码的,如果需要写入到 MFC 的 CString 类中(UNICODE),需要转换。
std::wstring wstr;
Poco::UnicodeConverter::toUTF16(chinese, wstr);
CString text = wstr.c_str();
// 将编码转换到 utf8(项目是 UNICODE 的情况下)
std::string toUTF8(const wchar_t* utf16String)
{
std::string utf8String;
Poco::UnicodeConverter::toUTF8(utf16String, utf8String);
return utf8String;
}
以上代码在 VC2010 中测试通过。