xmlconfig.cpp 2.5 KB

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