XML 版本的 ControlManager 实现
<languages>
<language id="en">
<text key="greeting">Hello</text>
<text key="farewell">Goodbye</text>
<text key="welcome">Welcome to the application</text>
</language>
<language id="zh">
<text key="greeting">你好</text>
<text key="farewell">再见</text>
<text key="welcome">欢迎使用该应用</text>
</language>
</languages>
#include <tinyxml2.h>
#include <string>
#include <unordered_map>
#include <iostream>
class XmlControlManager : public ControlManager {
private:
std::unordered_map<std::string, std::unordered_map<std::string, std::string>> languageData; // 存储语言数据
std::string currentLanguage; // 当前语言
public:
// 加载语言包
bool loadLanguagePack(const std::string& filePath) override {
tinyxml2::XMLDocument doc;
if (doc.LoadFile(filePath.c_str()) != tinyxml2::XML_SUCCESS) {
std::cerr << "Failed to load XML file: " << filePath << std::endl;
return false;
}
tinyxml2::XMLElement* root = doc.FirstChildElement("languages");
if (!root) {
std::cerr << "Invalid XML format: Missing <languages> root element" << std::endl;
return false;
}
// 遍历所有 <language> 元素
tinyxml2::XMLElement* languageElement = root->FirstChildElement("language");
while (languageElement) {
const char* langId = languageElement->Attribute("id");
if (!langId) {
std::cerr << "Invalid XML format: Missing language id attribute" << std::endl;
languageElement = languageElement->NextSiblingElement("language");
continue;
}
std::string lang = langId;
languageData[lang] = {}; // 初始化语言数据
// 遍历 <text> 元素
tinyxml2::XMLElement* textElement = languageElement->FirstChildElement("text");
while (textElement) {
const char* key = textElement->Attribute("key");
const char* value = textElement->GetText();
if (key && value) {
languageData[lang][key] = value;
}
textElement = textElement->NextSiblingElement("text");
}
languageElement = languageElement->NextSiblingElement("language");
}
return true;
}
// 切换语言
void setLanguage(const std::string& language) override {
if (languageData.find(language) != languageData.end()) {
currentLanguage = language;
} else {
std::cerr << "Language not found: " << language << std::endl;
}
}
// 获取文本内容
std::string getText(const std::string& key) const override {
auto langIt = languageData.find(currentLanguage);
if (langIt != languageData.end()) {
auto textIt = langIt->second.find(key);
if (textIt != langIt->second.end()) {
return textIt->second;
}
}
return "[Missing Text]";
}
// 检查键是否存在
bool hasKey(const std::string& key) const override {
auto langIt = languageData.find(currentLanguage);
if (langIt != languageData.end()) {
return langIt->second.find(key) != langIt->second.end();
}
return false;
}
};
Greeting (en): Hello
Farewell (en): Goodbye
Greeting (zh): 你好
Farewell (zh): 再见
Welcome (zh): 欢迎使用该应用
原文地址:https://blog.csdn.net/heroinsky/article/details/144079321
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!