xmlconfig.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "xmlconfig.h"
  2. #include <map>
  3. #include <utils/logger.h>
  4. namespace settings {
  5. XmlConfig::XmlConfig() {}
  6. XmlConfig::~XmlConfig() {}
  7. bool XmlConfig::Load(const std::string &path)
  8. {
  9. tinyxml2::XMLError err = xmlDocument_.LoadFile(path.c_str());
  10. if (err != tinyxml2::XML_SUCCESS) {
  11. HTELINK_LOG_ERR(
  12. "load %s failed, %d", path.c_str(), static_cast<int32_t>(err));
  13. return false;
  14. }
  15. return true;
  16. }
  17. void XmlConfig::GetElemValue(const std::string &father, std::function<void(std::map<std::string, std::string> &)> func)
  18. {
  19. xmlRoot_ = xmlDocument_.RootElement();
  20. if (!xmlRoot_) {
  21. HTELINK_LOG_ERR("XML ROOT is nullptr, %s", father.c_str());
  22. return;
  23. }
  24. tinyxml2::XMLElement *fatherEle = xmlRoot_;
  25. if (father == "") {
  26. fatherEle = xmlRoot_->FirstChildElement(father.c_str());
  27. if (!fatherEle) {
  28. HTELINK_LOG_ERR("XML ROOT no father element %s", father.c_str());
  29. return;
  30. }
  31. }
  32. for (tinyxml2::XMLElement *book = xmlRoot_->FirstChildElement(father.c_str()); book != nullptr;
  33. book = book->NextSiblingElement(father.c_str())) {
  34. std::map<std::string, std::string> kv;
  35. for (tinyxml2::XMLElement *elem = book->FirstChildElement(); elem != nullptr;
  36. elem = elem->NextSiblingElement()) {
  37. kv[elem->Name()] = elem->GetText();
  38. }
  39. func(kv);
  40. }
  41. }
  42. const std::string XmlConfig::GetElemValueString(const std::string &father, const std::string elem)
  43. {
  44. xmlRoot_ = xmlDocument_.RootElement();
  45. if (!xmlRoot_) {
  46. HTELINK_LOG_ERR("XML ROOT is nullptr, %s", elem.c_str());
  47. return "";
  48. }
  49. tinyxml2::XMLElement *fatherEle = xmlRoot_;
  50. if (father != "") {
  51. fatherEle = xmlRoot_->FirstChildElement(father.c_str());
  52. if (!fatherEle) {
  53. HTELINK_LOG_ERR("XML ROOT no father element %s", father.c_str());
  54. return "";
  55. }
  56. }
  57. tinyxml2::XMLElement *xmlEle = fatherEle->FirstChildElement(elem.c_str());
  58. if (!xmlEle) {
  59. HTELINK_LOG_ERR("XML ROOT no child element %s", elem.c_str());
  60. return "";
  61. }
  62. return xmlEle->GetText();
  63. }
  64. const int32_t XmlConfig::GetElemValueInt(const std::string &father, const std::string elem)
  65. {
  66. std::string result = GetElemValueString(father, elem);
  67. return atoi(result.c_str());
  68. }
  69. const bool XmlConfig::GetElemValueBool(const std::string &father, const std::string elem)
  70. {
  71. std::string result = GetElemValueString(father, elem);
  72. return atoi(result.c_str()) != 0;
  73. }
  74. } // namespace settings