1 #include "stdafx.h"
2 #include "TinyXml2Helper.h"
3 #include "Common.h"
4
LoadXmlFile(tinyxml2::XMLDocument & doc,const wchar_t * file_path)5 bool CTinyXml2Helper::LoadXmlFile(tinyxml2::XMLDocument& doc, const wchar_t* file_path)
6 {
7 //由于XMLDocument::LoadFile函数不支持Unicode,因此这里自行读取文件内容,并调用XMLDocument::Parse函数解析
8 size_t length;
9 const char* xml_contents = CCommon::GetFileContent(file_path, length);
10 auto err = doc.Parse(xml_contents, length);
11 delete[] xml_contents;
12 return err == tinyxml2::XML_SUCCESS;
13 }
14
IterateChildNode(tinyxml2::XMLElement * ele,std::function<void (tinyxml2::XMLElement *)> fun)15 void CTinyXml2Helper::IterateChildNode(tinyxml2::XMLElement* ele, std::function<void(tinyxml2::XMLElement*)> fun)
16 {
17 if (ele == nullptr)
18 return;
19
20 tinyxml2::XMLElement* child = ele->FirstChildElement();
21 if (child == nullptr)
22 return;
23 fun(child);
24 while (true)
25 {
26 child = child->NextSiblingElement();
27 if (child != nullptr)
28 fun(child);
29 else
30 break;
31 }
32 }
33
ElementAttribute(tinyxml2::XMLElement * ele,const char * attr)34 const char * CTinyXml2Helper::ElementAttribute(tinyxml2::XMLElement * ele, const char * attr)
35 {
36 if (ele != nullptr)
37 {
38 const char* str = ele->Attribute(attr);
39 if (str != nullptr)
40 return str;
41 }
42 return "";
43 }
44
ElementName(tinyxml2::XMLElement * ele)45 const char* CTinyXml2Helper::ElementName(tinyxml2::XMLElement* ele)
46 {
47 if (ele != nullptr)
48 {
49 const char* str = ele->Name();
50 if (str != nullptr)
51 return str;
52 }
53 return "";
54 }
55
ElementText(tinyxml2::XMLElement * ele)56 const char* CTinyXml2Helper::ElementText(tinyxml2::XMLElement* ele)
57 {
58 if (ele != nullptr)
59 {
60 const char* str = ele->GetText();
61 if (str != nullptr)
62 return str;
63 }
64 return "";
65 }
66
StringToBool(const char * str)67 bool CTinyXml2Helper::StringToBool(const char* str)
68 {
69 string str_text{ str };
70 return (!str_text.empty() && (str_text == "true" || str_text == "1"));
71 }
72
GetElementAttributeBool(tinyxml2::XMLElement * ele,const char * attr,bool & value)73 void CTinyXml2Helper::GetElementAttributeBool(tinyxml2::XMLElement* ele, const char* attr, bool& value)
74 {
75 std::string str_attr = CTinyXml2Helper::ElementAttribute(ele, attr);
76 if (!str_attr.empty())
77 value = CTinyXml2Helper::StringToBool(str_attr.c_str());
78 }
79
GetElementAttributeInt(tinyxml2::XMLElement * ele,const char * attr,int & value)80 void CTinyXml2Helper::GetElementAttributeInt(tinyxml2::XMLElement* ele, const char* attr, int& value)
81 {
82 std::string str_attr = CTinyXml2Helper::ElementAttribute(ele, attr);
83 if (!str_attr.empty())
84 value = atoi(str_attr.c_str());
85 }
86
87