tinyxml2.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937
  1. /*
  2. Original code by Lee Thomason (www.grinninglizard.com)
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any
  5. damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any
  7. purpose, including commercial applications, and to alter it and
  8. redistribute it freely, subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must
  10. not claim that you wrote the original software. If you use this
  11. software in a product, an acknowledgment in the product documentation
  12. would be appreciated but is not required.
  13. 2. Altered source versions must be plainly marked as such, and
  14. must not be misrepresented as being the original software.
  15. 3. This notice may not be removed or altered from any source
  16. distribution.
  17. */
  18. #include "tinyxml2.h"
  19. #include <new> // yes, this one new style header, is in the Android SDK.
  20. #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
  21. #include <stddef.h>
  22. #include <stdarg.h>
  23. #else
  24. #include <cstddef>
  25. #include <cstdarg>
  26. #endif
  27. #if defined(_MSC_VER) && (_MSC_VER >= 1400) && (!defined WINCE)
  28. // Microsoft Visual Studio, version 2005 and higher. Not WinCE.
  29. /*int _snprintf_s(
  30. char *buffer,
  31. size_t sizeOfBuffer,
  32. size_t count,
  33. const char *format [,
  34. argument] ...
  35. );*/
  36. static inline int TIXML_SNPRINTF(char* buffer, size_t size, const char* format, ...)
  37. {
  38. va_list va;
  39. va_start(va, format);
  40. int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va);
  41. va_end(va);
  42. return result;
  43. }
  44. static inline int TIXML_VSNPRINTF(char* buffer, size_t size, const char* format, va_list va)
  45. {
  46. int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va);
  47. return result;
  48. }
  49. #define TIXML_VSCPRINTF _vscprintf
  50. #define TIXML_SSCANF sscanf_s
  51. #elif defined _MSC_VER
  52. // Microsoft Visual Studio 2003 and earlier or WinCE
  53. #define TIXML_SNPRINTF _snprintf
  54. #define TIXML_VSNPRINTF _vsnprintf
  55. #define TIXML_SSCANF sscanf
  56. #if (_MSC_VER < 1400) && (!defined WINCE)
  57. // Microsoft Visual Studio 2003 and not WinCE.
  58. #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have.
  59. #else
  60. // Microsoft Visual Studio 2003 and earlier or WinCE.
  61. static inline int TIXML_VSCPRINTF(const char* format, va_list va)
  62. {
  63. int len = 512;
  64. for (;;)
  65. {
  66. len = len * 2;
  67. char* str = new char[len]();
  68. const int required = _vsnprintf(str, len, format, va);
  69. delete[] str;
  70. if (required != -1)
  71. {
  72. TIXMLASSERT(required >= 0);
  73. len = required;
  74. break;
  75. }
  76. }
  77. TIXMLASSERT(len >= 0);
  78. return len;
  79. }
  80. #endif
  81. #else
  82. // GCC version 3 and higher
  83. //#warning( "Using sn* functions." )
  84. #define TIXML_SNPRINTF snprintf
  85. #define TIXML_VSNPRINTF vsnprintf
  86. static inline int TIXML_VSCPRINTF(const char* format, va_list va)
  87. {
  88. int len = vsnprintf(0, 0, format, va);
  89. TIXMLASSERT(len >= 0);
  90. return len;
  91. }
  92. #define TIXML_SSCANF sscanf
  93. #endif
  94. static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF
  95. static const char LF = LINE_FEED;
  96. static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out
  97. static const char CR = CARRIAGE_RETURN;
  98. static const char SINGLE_QUOTE = '\'';
  99. static const char DOUBLE_QUOTE = '\"';
  100. // Bunch of unicode info at:
  101. // http://www.unicode.org/faq/utf_bom.html
  102. // ef bb bf (Microsoft "lead bytes") - designates UTF-8
  103. static const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
  104. static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
  105. static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
  106. namespace tinyxml2
  107. {
  108. struct Entity
  109. {
  110. const char* pattern;
  111. int length;
  112. char value;
  113. };
  114. static const int NUM_ENTITIES = 5;
  115. static const Entity entities[NUM_ENTITIES] = {
  116. {"quot", 4, DOUBLE_QUOTE},
  117. {"amp", 3, '&'},
  118. {"apos", 4, SINGLE_QUOTE},
  119. {"lt", 2, '<'},
  120. {"gt", 2, '>'}};
  121. StrPair::~StrPair()
  122. {
  123. Reset();
  124. }
  125. void StrPair::TransferTo(StrPair* other)
  126. {
  127. if (this == other)
  128. {
  129. return;
  130. }
  131. // This in effect implements the assignment operator by "moving"
  132. // ownership (as in auto_ptr).
  133. TIXMLASSERT(other != 0);
  134. TIXMLASSERT(other->_flags == 0);
  135. TIXMLASSERT(other->_start == 0);
  136. TIXMLASSERT(other->_end == 0);
  137. other->Reset();
  138. other->_flags = _flags;
  139. other->_start = _start;
  140. other->_end = _end;
  141. _flags = 0;
  142. _start = 0;
  143. _end = 0;
  144. }
  145. void StrPair::Reset()
  146. {
  147. if (_flags & NEEDS_DELETE)
  148. {
  149. delete[] _start;
  150. }
  151. _flags = 0;
  152. _start = 0;
  153. _end = 0;
  154. }
  155. void StrPair::SetStr(const char* str, int flags)
  156. {
  157. TIXMLASSERT(str);
  158. Reset();
  159. size_t len = strlen(str);
  160. TIXMLASSERT(_start == 0);
  161. _start = new char[len + 1];
  162. memcpy(_start, str, len + 1);
  163. _end = _start + len;
  164. _flags = flags | NEEDS_DELETE;
  165. }
  166. char* StrPair::ParseText(char* p, const char* endTag, int strFlags, int* curLineNumPtr)
  167. {
  168. TIXMLASSERT(p);
  169. TIXMLASSERT(endTag && *endTag);
  170. TIXMLASSERT(curLineNumPtr);
  171. char* start = p;
  172. char endChar = *endTag;
  173. size_t length = strlen(endTag);
  174. // Inner loop of text parsing.
  175. while (*p)
  176. {
  177. if (*p == endChar && strncmp(p, endTag, length) == 0)
  178. {
  179. Set(start, p, strFlags);
  180. return p + length;
  181. }
  182. else if (*p == '\n')
  183. {
  184. ++(*curLineNumPtr);
  185. }
  186. ++p;
  187. TIXMLASSERT(p);
  188. }
  189. return 0;
  190. }
  191. char* StrPair::ParseName(char* p)
  192. {
  193. if (!p || !(*p))
  194. {
  195. return 0;
  196. }
  197. if (!XMLUtil::IsNameStartChar(*p))
  198. {
  199. return 0;
  200. }
  201. char* const start = p;
  202. ++p;
  203. while (*p && XMLUtil::IsNameChar(*p))
  204. {
  205. ++p;
  206. }
  207. Set(start, p, 0);
  208. return p;
  209. }
  210. void StrPair::CollapseWhitespace()
  211. {
  212. // Adjusting _start would cause undefined behavior on delete[]
  213. TIXMLASSERT((_flags & NEEDS_DELETE) == 0);
  214. // Trim leading space.
  215. _start = XMLUtil::SkipWhiteSpace(_start, 0);
  216. if (*_start)
  217. {
  218. const char* p = _start; // the read pointer
  219. char* q = _start; // the write pointer
  220. while (*p)
  221. {
  222. if (XMLUtil::IsWhiteSpace(*p))
  223. {
  224. p = XMLUtil::SkipWhiteSpace(p, 0);
  225. if (*p == 0)
  226. {
  227. break; // don't write to q; this trims the trailing space.
  228. }
  229. *q = ' ';
  230. ++q;
  231. }
  232. *q = *p;
  233. ++q;
  234. ++p;
  235. }
  236. *q = 0;
  237. }
  238. }
  239. const char* StrPair::GetStr()
  240. {
  241. TIXMLASSERT(_start);
  242. TIXMLASSERT(_end);
  243. if (_flags & NEEDS_FLUSH)
  244. {
  245. *_end = 0;
  246. _flags ^= NEEDS_FLUSH;
  247. if (_flags)
  248. {
  249. const char* p = _start; // the read pointer
  250. char* q = _start; // the write pointer
  251. while (p < _end)
  252. {
  253. if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR)
  254. {
  255. // CR-LF pair becomes LF
  256. // CR alone becomes LF
  257. // LF-CR becomes LF
  258. if (*(p + 1) == LF)
  259. {
  260. p += 2;
  261. }
  262. else
  263. {
  264. ++p;
  265. }
  266. *q = LF;
  267. ++q;
  268. }
  269. else if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF)
  270. {
  271. if (*(p + 1) == CR)
  272. {
  273. p += 2;
  274. }
  275. else
  276. {
  277. ++p;
  278. }
  279. *q = LF;
  280. ++q;
  281. }
  282. else if ((_flags & NEEDS_ENTITY_PROCESSING) && *p == '&')
  283. {
  284. // Entities handled by tinyXML2:
  285. // - special entities in the entity table [in/out]
  286. // - numeric character reference [in]
  287. // &#20013; or &#x4e2d;
  288. if (*(p + 1) == '#')
  289. {
  290. const int buflen = 10;
  291. char buf[buflen] = {0};
  292. int len = 0;
  293. char* adjusted = const_cast<char*>(XMLUtil::GetCharacterRef(p, buf, &len));
  294. if (adjusted == 0)
  295. {
  296. *q = *p;
  297. ++p;
  298. ++q;
  299. }
  300. else
  301. {
  302. TIXMLASSERT(0 <= len && len <= buflen);
  303. TIXMLASSERT(q + len <= adjusted);
  304. p = adjusted;
  305. memcpy(q, buf, len);
  306. q += len;
  307. }
  308. }
  309. else
  310. {
  311. bool entityFound = false;
  312. for (int i = 0; i < NUM_ENTITIES; ++i)
  313. {
  314. const Entity& entity = entities[i];
  315. if (strncmp(p + 1, entity.pattern, entity.length) == 0 && *(p + entity.length + 1) == ';')
  316. {
  317. // Found an entity - convert.
  318. *q = entity.value;
  319. ++q;
  320. p += entity.length + 2;
  321. entityFound = true;
  322. break;
  323. }
  324. }
  325. if (!entityFound)
  326. {
  327. // fixme: treat as error?
  328. ++p;
  329. ++q;
  330. }
  331. }
  332. }
  333. else
  334. {
  335. *q = *p;
  336. ++p;
  337. ++q;
  338. }
  339. }
  340. *q = 0;
  341. }
  342. // The loop below has plenty going on, and this
  343. // is a less useful mode. Break it out.
  344. if (_flags & NEEDS_WHITESPACE_COLLAPSING)
  345. {
  346. CollapseWhitespace();
  347. }
  348. _flags = (_flags & NEEDS_DELETE);
  349. }
  350. TIXMLASSERT(_start);
  351. return _start;
  352. }
  353. // --------- XMLUtil ----------- //
  354. const char* XMLUtil::writeBoolTrue = "true";
  355. const char* XMLUtil::writeBoolFalse = "false";
  356. void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse)
  357. {
  358. static const char* defTrue = "true";
  359. static const char* defFalse = "false";
  360. writeBoolTrue = (writeTrue) ? writeTrue : defTrue;
  361. writeBoolFalse = (writeFalse) ? writeFalse : defFalse;
  362. }
  363. const char* XMLUtil::ReadBOM(const char* p, bool* bom)
  364. {
  365. TIXMLASSERT(p);
  366. TIXMLASSERT(bom);
  367. *bom = false;
  368. const unsigned char* pu = reinterpret_cast<const unsigned char*>(p);
  369. // Check for BOM:
  370. if (*(pu + 0) == TIXML_UTF_LEAD_0 && *(pu + 1) == TIXML_UTF_LEAD_1 && *(pu + 2) == TIXML_UTF_LEAD_2)
  371. {
  372. *bom = true;
  373. p += 3;
  374. }
  375. TIXMLASSERT(p);
  376. return p;
  377. }
  378. void XMLUtil::ConvertUTF32ToUTF8(unsigned long input, char* output, int* length)
  379. {
  380. const unsigned long BYTE_MASK = 0xBF;
  381. const unsigned long BYTE_MARK = 0x80;
  382. const unsigned long FIRST_BYTE_MARK[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC};
  383. if (input < 0x80)
  384. {
  385. *length = 1;
  386. }
  387. else if (input < 0x800)
  388. {
  389. *length = 2;
  390. }
  391. else if (input < 0x10000)
  392. {
  393. *length = 3;
  394. }
  395. else if (input < 0x200000)
  396. {
  397. *length = 4;
  398. }
  399. else
  400. {
  401. *length = 0; // This code won't convert this correctly anyway.
  402. return;
  403. }
  404. output += *length;
  405. // Scary scary fall throughs are annotated with carefully designed comments
  406. // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc
  407. switch (*length)
  408. {
  409. case 4:
  410. --output;
  411. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  412. input >>= 6;
  413. //fall through
  414. case 3:
  415. --output;
  416. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  417. input >>= 6;
  418. //fall through
  419. case 2:
  420. --output;
  421. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  422. input >>= 6;
  423. //fall through
  424. case 1:
  425. --output;
  426. *output = (char)(input | FIRST_BYTE_MARK[*length]);
  427. break;
  428. default:
  429. TIXMLASSERT(false);
  430. }
  431. }
  432. const char* XMLUtil::GetCharacterRef(const char* p, char* value, int* length)
  433. {
  434. // Presume an entity, and pull it out.
  435. *length = 0;
  436. if (*(p + 1) == '#' && *(p + 2))
  437. {
  438. unsigned long ucs = 0;
  439. TIXMLASSERT(sizeof(ucs) >= 4);
  440. ptrdiff_t delta = 0;
  441. unsigned mult = 1;
  442. static const char SEMICOLON = ';';
  443. if (*(p + 2) == 'x')
  444. {
  445. // Hexadecimal.
  446. const char* q = p + 3;
  447. if (!(*q))
  448. {
  449. return 0;
  450. }
  451. q = strchr(q, SEMICOLON);
  452. if (!q)
  453. {
  454. return 0;
  455. }
  456. TIXMLASSERT(*q == SEMICOLON);
  457. delta = q - p;
  458. --q;
  459. while (*q != 'x')
  460. {
  461. unsigned int digit = 0;
  462. if (*q >= '0' && *q <= '9')
  463. {
  464. digit = *q - '0';
  465. }
  466. else if (*q >= 'a' && *q <= 'f')
  467. {
  468. digit = *q - 'a' + 10;
  469. }
  470. else if (*q >= 'A' && *q <= 'F')
  471. {
  472. digit = *q - 'A' + 10;
  473. }
  474. else
  475. {
  476. return 0;
  477. }
  478. TIXMLASSERT(digit < 16);
  479. TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit);
  480. const unsigned int digitScaled = mult * digit;
  481. TIXMLASSERT(ucs <= ULONG_MAX - digitScaled);
  482. ucs += digitScaled;
  483. TIXMLASSERT(mult <= UINT_MAX / 16);
  484. mult *= 16;
  485. --q;
  486. }
  487. }
  488. else
  489. {
  490. // Decimal.
  491. const char* q = p + 2;
  492. if (!(*q))
  493. {
  494. return 0;
  495. }
  496. q = strchr(q, SEMICOLON);
  497. if (!q)
  498. {
  499. return 0;
  500. }
  501. TIXMLASSERT(*q == SEMICOLON);
  502. delta = q - p;
  503. --q;
  504. while (*q != '#')
  505. {
  506. if (*q >= '0' && *q <= '9')
  507. {
  508. const unsigned int digit = *q - '0';
  509. TIXMLASSERT(digit < 10);
  510. TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit);
  511. const unsigned int digitScaled = mult * digit;
  512. TIXMLASSERT(ucs <= ULONG_MAX - digitScaled);
  513. ucs += digitScaled;
  514. }
  515. else
  516. {
  517. return 0;
  518. }
  519. TIXMLASSERT(mult <= UINT_MAX / 10);
  520. mult *= 10;
  521. --q;
  522. }
  523. }
  524. // convert the UCS to UTF-8
  525. ConvertUTF32ToUTF8(ucs, value, length);
  526. return p + delta + 1;
  527. }
  528. return p + 1;
  529. }
  530. void XMLUtil::ToStr(int v, char* buffer, int bufferSize)
  531. {
  532. TIXML_SNPRINTF(buffer, bufferSize, "%d", v);
  533. }
  534. void XMLUtil::ToStr(unsigned v, char* buffer, int bufferSize)
  535. {
  536. TIXML_SNPRINTF(buffer, bufferSize, "%u", v);
  537. }
  538. void XMLUtil::ToStr(bool v, char* buffer, int bufferSize)
  539. {
  540. TIXML_SNPRINTF(buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse);
  541. }
  542. /*
  543. ToStr() of a number is a very tricky topic.
  544. https://github.com/leethomason/tinyxml2/issues/106
  545. */
  546. void XMLUtil::ToStr(float v, char* buffer, int bufferSize)
  547. {
  548. TIXML_SNPRINTF(buffer, bufferSize, "%.8g", v);
  549. }
  550. void XMLUtil::ToStr(double v, char* buffer, int bufferSize)
  551. {
  552. TIXML_SNPRINTF(buffer, bufferSize, "%.17g", v);
  553. }
  554. void XMLUtil::ToStr(xml_Int64a_t v, char* buffer, int bufferSize)
  555. {
  556. // horrible syntax trick to make the compiler happy about %lld
  557. TIXML_SNPRINTF(buffer, bufferSize, "%lld", (long long)v);
  558. }
  559. bool XMLUtil::ToInt(const char* str, int* value)
  560. {
  561. if (TIXML_SSCANF(str, "%d", value) == 1)
  562. {
  563. return true;
  564. }
  565. return false;
  566. }
  567. bool XMLUtil::ToUnsigned(const char* str, unsigned* value)
  568. {
  569. if (TIXML_SSCANF(str, "%u", value) == 1)
  570. {
  571. return true;
  572. }
  573. return false;
  574. }
  575. bool XMLUtil::ToBool(const char* str, bool* value)
  576. {
  577. int ival = 0;
  578. if (ToInt(str, &ival))
  579. {
  580. *value = (ival == 0) ? false : true;
  581. return true;
  582. }
  583. if (StringEqual(str, "true"))
  584. {
  585. *value = true;
  586. return true;
  587. }
  588. else if (StringEqual(str, "false"))
  589. {
  590. *value = false;
  591. return true;
  592. }
  593. return false;
  594. }
  595. bool XMLUtil::ToFloat(const char* str, float* value)
  596. {
  597. if (TIXML_SSCANF(str, "%f", value) == 1)
  598. {
  599. return true;
  600. }
  601. return false;
  602. }
  603. bool XMLUtil::ToDouble(const char* str, double* value)
  604. {
  605. if (TIXML_SSCANF(str, "%lf", value) == 1)
  606. {
  607. return true;
  608. }
  609. return false;
  610. }
  611. bool XMLUtil::ToInt64(const char* str, xml_Int64a_t* value)
  612. {
  613. long long v = 0; // horrible syntax trick to make the compiler happy about %lld
  614. if (TIXML_SSCANF(str, "%lld", &v) == 1)
  615. {
  616. *value = (xml_Int64a_t)v;
  617. return true;
  618. }
  619. return false;
  620. }
  621. char* XMLDocument::Identify(char* p, XMLNode** node)
  622. {
  623. TIXMLASSERT(node);
  624. TIXMLASSERT(p);
  625. char* const start = p;
  626. int const startLine = _parseCurLineNum;
  627. p = XMLUtil::SkipWhiteSpace(p, &_parseCurLineNum);
  628. if (!*p)
  629. {
  630. *node = 0;
  631. TIXMLASSERT(p);
  632. return p;
  633. }
  634. // These strings define the matching patterns:
  635. static const char* xmlHeader = {"<?"};
  636. static const char* commentHeader = {"<!--"};
  637. static const char* cdataHeader = {"<![CDATA["};
  638. static const char* dtdHeader = {"<!"};
  639. static const char* elementHeader = {"<"}; // and a header for everything else; check last.
  640. static const int xmlHeaderLen = 2;
  641. static const int commentHeaderLen = 4;
  642. static const int cdataHeaderLen = 9;
  643. static const int dtdHeaderLen = 2;
  644. static const int elementHeaderLen = 1;
  645. TIXMLASSERT(sizeof(XMLComment) == sizeof(XMLUnknown)); // use same memory pool
  646. TIXMLASSERT(sizeof(XMLComment) == sizeof(XMLDeclaration)); // use same memory pool
  647. XMLNode* returnNode = 0;
  648. if (XMLUtil::StringEqual(p, xmlHeader, xmlHeaderLen))
  649. {
  650. returnNode = CreateUnlinkedNode<XMLDeclaration>(_commentPool);
  651. returnNode->_parseLineNum = _parseCurLineNum;
  652. p += xmlHeaderLen;
  653. }
  654. else if (XMLUtil::StringEqual(p, commentHeader, commentHeaderLen))
  655. {
  656. returnNode = CreateUnlinkedNode<XMLComment>(_commentPool);
  657. returnNode->_parseLineNum = _parseCurLineNum;
  658. p += commentHeaderLen;
  659. }
  660. else if (XMLUtil::StringEqual(p, cdataHeader, cdataHeaderLen))
  661. {
  662. XMLText* text = CreateUnlinkedNode<XMLText>(_textPool);
  663. returnNode = text;
  664. returnNode->_parseLineNum = _parseCurLineNum;
  665. p += cdataHeaderLen;
  666. text->SetCData(true);
  667. }
  668. else if (XMLUtil::StringEqual(p, dtdHeader, dtdHeaderLen))
  669. {
  670. returnNode = CreateUnlinkedNode<XMLUnknown>(_commentPool);
  671. returnNode->_parseLineNum = _parseCurLineNum;
  672. p += dtdHeaderLen;
  673. }
  674. else if (XMLUtil::StringEqual(p, elementHeader, elementHeaderLen))
  675. {
  676. returnNode = CreateUnlinkedNode<XMLElement>(_elementPool);
  677. returnNode->_parseLineNum = _parseCurLineNum;
  678. p += elementHeaderLen;
  679. }
  680. else
  681. {
  682. returnNode = CreateUnlinkedNode<XMLText>(_textPool);
  683. returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character
  684. p = start; // Back it up, all the text counts.
  685. _parseCurLineNum = startLine;
  686. }
  687. TIXMLASSERT(returnNode);
  688. TIXMLASSERT(p);
  689. *node = returnNode;
  690. return p;
  691. }
  692. bool XMLDocument::Accept(XMLVisitor* visitor) const
  693. {
  694. TIXMLASSERT(visitor);
  695. if (visitor->VisitEnter(*this))
  696. {
  697. for (const XMLNode* node = FirstChild(); node; node = node->NextSibling())
  698. {
  699. if (!node->Accept(visitor))
  700. {
  701. break;
  702. }
  703. }
  704. }
  705. return visitor->VisitExit(*this);
  706. }
  707. // --------- XMLNode ----------- //
  708. XMLNode::XMLNode(XMLDocument* doc) : _document(doc),
  709. _parent(0),
  710. _value(),
  711. _parseLineNum(0),
  712. _firstChild(0),
  713. _lastChild(0),
  714. _prev(0),
  715. _next(0),
  716. _userData(0),
  717. _memPool(0)
  718. {
  719. }
  720. XMLNode::~XMLNode()
  721. {
  722. DeleteChildren();
  723. if (_parent)
  724. {
  725. _parent->Unlink(this);
  726. }
  727. }
  728. const char* XMLNode::Value() const
  729. {
  730. // Edge case: XMLDocuments don't have a Value. Return null.
  731. if (this->ToDocument())
  732. return 0;
  733. return _value.GetStr();
  734. }
  735. void XMLNode::SetValue(const char* str, bool staticMem)
  736. {
  737. if (staticMem)
  738. {
  739. _value.SetInternedStr(str);
  740. }
  741. else
  742. {
  743. _value.SetStr(str);
  744. }
  745. }
  746. XMLNode* XMLNode::DeepClone(XMLDocument* target) const
  747. {
  748. XMLNode* clone = this->ShallowClone(target);
  749. if (!clone) return 0;
  750. for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling())
  751. {
  752. XMLNode* childClone = child->DeepClone(target);
  753. TIXMLASSERT(childClone);
  754. clone->InsertEndChild(childClone);
  755. }
  756. return clone;
  757. }
  758. void XMLNode::DeleteChildren()
  759. {
  760. while (_firstChild)
  761. {
  762. TIXMLASSERT(_lastChild);
  763. DeleteChild(_firstChild);
  764. }
  765. _firstChild = _lastChild = 0;
  766. }
  767. void XMLNode::Unlink(XMLNode* child)
  768. {
  769. TIXMLASSERT(child);
  770. TIXMLASSERT(child->_document == _document);
  771. TIXMLASSERT(child->_parent == this);
  772. if (child == _firstChild)
  773. {
  774. _firstChild = _firstChild->_next;
  775. }
  776. if (child == _lastChild)
  777. {
  778. _lastChild = _lastChild->_prev;
  779. }
  780. if (child->_prev)
  781. {
  782. child->_prev->_next = child->_next;
  783. }
  784. if (child->_next)
  785. {
  786. child->_next->_prev = child->_prev;
  787. }
  788. child->_next = 0;
  789. child->_prev = 0;
  790. child->_parent = 0;
  791. }
  792. void XMLNode::DeleteChild(XMLNode* node)
  793. {
  794. TIXMLASSERT(node);
  795. TIXMLASSERT(node->_document == _document);
  796. TIXMLASSERT(node->_parent == this);
  797. Unlink(node);
  798. TIXMLASSERT(node->_prev == 0);
  799. TIXMLASSERT(node->_next == 0);
  800. TIXMLASSERT(node->_parent == 0);
  801. DeleteNode(node);
  802. }
  803. XMLNode* XMLNode::InsertEndChild(XMLNode* addThis)
  804. {
  805. TIXMLASSERT(addThis);
  806. if (addThis->_document != _document)
  807. {
  808. TIXMLASSERT(false);
  809. return 0;
  810. }
  811. InsertChildPreamble(addThis);
  812. if (_lastChild)
  813. {
  814. TIXMLASSERT(_firstChild);
  815. TIXMLASSERT(_lastChild->_next == 0);
  816. _lastChild->_next = addThis;
  817. addThis->_prev = _lastChild;
  818. _lastChild = addThis;
  819. addThis->_next = 0;
  820. }
  821. else
  822. {
  823. TIXMLASSERT(_firstChild == 0);
  824. _firstChild = _lastChild = addThis;
  825. addThis->_prev = 0;
  826. addThis->_next = 0;
  827. }
  828. addThis->_parent = this;
  829. return addThis;
  830. }
  831. XMLNode* XMLNode::InsertFirstChild(XMLNode* addThis)
  832. {
  833. TIXMLASSERT(addThis);
  834. if (addThis->_document != _document)
  835. {
  836. TIXMLASSERT(false);
  837. return 0;
  838. }
  839. InsertChildPreamble(addThis);
  840. if (_firstChild)
  841. {
  842. TIXMLASSERT(_lastChild);
  843. TIXMLASSERT(_firstChild->_prev == 0);
  844. _firstChild->_prev = addThis;
  845. addThis->_next = _firstChild;
  846. _firstChild = addThis;
  847. addThis->_prev = 0;
  848. }
  849. else
  850. {
  851. TIXMLASSERT(_lastChild == 0);
  852. _firstChild = _lastChild = addThis;
  853. addThis->_prev = 0;
  854. addThis->_next = 0;
  855. }
  856. addThis->_parent = this;
  857. return addThis;
  858. }
  859. XMLNode* XMLNode::InsertAfterChild(XMLNode* afterThis, XMLNode* addThis)
  860. {
  861. TIXMLASSERT(addThis);
  862. if (addThis->_document != _document)
  863. {
  864. TIXMLASSERT(false);
  865. return 0;
  866. }
  867. TIXMLASSERT(afterThis);
  868. if (afterThis->_parent != this)
  869. {
  870. TIXMLASSERT(false);
  871. return 0;
  872. }
  873. if (afterThis == addThis)
  874. {
  875. // Current state: BeforeThis -> AddThis -> OneAfterAddThis
  876. // Now AddThis must disappear from it's location and then
  877. // reappear between BeforeThis and OneAfterAddThis.
  878. // So just leave it where it is.
  879. return addThis;
  880. }
  881. if (afterThis->_next == 0)
  882. {
  883. // The last node or the only node.
  884. return InsertEndChild(addThis);
  885. }
  886. InsertChildPreamble(addThis);
  887. addThis->_prev = afterThis;
  888. addThis->_next = afterThis->_next;
  889. afterThis->_next->_prev = addThis;
  890. afterThis->_next = addThis;
  891. addThis->_parent = this;
  892. return addThis;
  893. }
  894. const XMLElement* XMLNode::FirstChildElement(const char* name) const
  895. {
  896. for (const XMLNode* node = _firstChild; node; node = node->_next)
  897. {
  898. const XMLElement* element = node->ToElementWithName(name);
  899. if (element)
  900. {
  901. return element;
  902. }
  903. }
  904. return 0;
  905. }
  906. const XMLElement* XMLNode::LastChildElement(const char* name) const
  907. {
  908. for (const XMLNode* node = _lastChild; node; node = node->_prev)
  909. {
  910. const XMLElement* element = node->ToElementWithName(name);
  911. if (element)
  912. {
  913. return element;
  914. }
  915. }
  916. return 0;
  917. }
  918. const XMLElement* XMLNode::NextSiblingElement(const char* name) const
  919. {
  920. for (const XMLNode* node = _next; node; node = node->_next)
  921. {
  922. const XMLElement* element = node->ToElementWithName(name);
  923. if (element)
  924. {
  925. return element;
  926. }
  927. }
  928. return 0;
  929. }
  930. const XMLElement* XMLNode::PreviousSiblingElement(const char* name) const
  931. {
  932. for (const XMLNode* node = _prev; node; node = node->_prev)
  933. {
  934. const XMLElement* element = node->ToElementWithName(name);
  935. if (element)
  936. {
  937. return element;
  938. }
  939. }
  940. return 0;
  941. }
  942. char* XMLNode::ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr)
  943. {
  944. // This is a recursive method, but thinking about it "at the current level"
  945. // it is a pretty simple flat list:
  946. // <foo/>
  947. // <!-- comment -->
  948. //
  949. // With a special case:
  950. // <foo>
  951. // </foo>
  952. // <!-- comment -->
  953. //
  954. // Where the closing element (/foo) *must* be the next thing after the opening
  955. // element, and the names must match. BUT the tricky bit is that the closing
  956. // element will be read by the child.
  957. //
  958. // 'endTag' is the end tag for this node, it is returned by a call to a child.
  959. // 'parentEnd' is the end tag for the parent, which is filled in and returned.
  960. XMLDocument::DepthTracker tracker(_document);
  961. if (_document->Error())
  962. return 0;
  963. while (p && *p)
  964. {
  965. XMLNode* node = 0;
  966. p = _document->Identify(p, &node);
  967. TIXMLASSERT(p);
  968. if (node == 0)
  969. {
  970. break;
  971. }
  972. int initialLineNum = node->_parseLineNum;
  973. StrPair endTag;
  974. p = node->ParseDeep(p, &endTag, curLineNumPtr);
  975. if (!p)
  976. {
  977. DeleteNode(node);
  978. if (!_document->Error())
  979. {
  980. _document->SetError(XML_ERROR_PARSING, initialLineNum, 0);
  981. }
  982. break;
  983. }
  984. XMLDeclaration* decl = node->ToDeclaration();
  985. if (decl)
  986. {
  987. // Declarations are only allowed at document level
  988. bool wellLocated = (ToDocument() != 0);
  989. if (wellLocated)
  990. {
  991. // Multiple declarations are allowed but all declarations
  992. // must occur before anything else
  993. for (const XMLNode* existingNode = _document->FirstChild(); existingNode; existingNode = existingNode->NextSibling())
  994. {
  995. if (!existingNode->ToDeclaration())
  996. {
  997. wellLocated = false;
  998. break;
  999. }
  1000. }
  1001. }
  1002. if (!wellLocated)
  1003. {
  1004. _document->SetError(XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value());
  1005. DeleteNode(node);
  1006. break;
  1007. }
  1008. }
  1009. XMLElement* ele = node->ToElement();
  1010. if (ele)
  1011. {
  1012. // We read the end tag. Return it to the parent.
  1013. if (ele->ClosingType() == XMLElement::CLOSING)
  1014. {
  1015. if (parentEndTag)
  1016. {
  1017. ele->_value.TransferTo(parentEndTag);
  1018. }
  1019. node->_memPool->SetTracked(); // created and then immediately deleted.
  1020. DeleteNode(node);
  1021. return p;
  1022. }
  1023. // Handle an end tag returned to this level.
  1024. // And handle a bunch of annoying errors.
  1025. bool mismatch = false;
  1026. if (endTag.Empty())
  1027. {
  1028. if (ele->ClosingType() == XMLElement::OPEN)
  1029. {
  1030. mismatch = true;
  1031. }
  1032. }
  1033. else
  1034. {
  1035. if (ele->ClosingType() != XMLElement::OPEN)
  1036. {
  1037. mismatch = true;
  1038. }
  1039. else if (!XMLUtil::StringEqual(endTag.GetStr(), ele->Name()))
  1040. {
  1041. mismatch = true;
  1042. }
  1043. }
  1044. if (mismatch)
  1045. {
  1046. _document->SetError(XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name());
  1047. DeleteNode(node);
  1048. break;
  1049. }
  1050. }
  1051. InsertEndChild(node);
  1052. }
  1053. return 0;
  1054. }
  1055. /*static*/ void XMLNode::DeleteNode(XMLNode* node)
  1056. {
  1057. if (node == 0)
  1058. {
  1059. return;
  1060. }
  1061. TIXMLASSERT(node->_document);
  1062. if (!node->ToDocument())
  1063. {
  1064. node->_document->MarkInUse(node);
  1065. }
  1066. MemPool* pool = node->_memPool;
  1067. node->~XMLNode();
  1068. pool->Free(node);
  1069. }
  1070. void XMLNode::InsertChildPreamble(XMLNode* insertThis) const
  1071. {
  1072. TIXMLASSERT(insertThis);
  1073. TIXMLASSERT(insertThis->_document == _document);
  1074. if (insertThis->_parent)
  1075. {
  1076. insertThis->_parent->Unlink(insertThis);
  1077. }
  1078. else
  1079. {
  1080. insertThis->_document->MarkInUse(insertThis);
  1081. insertThis->_memPool->SetTracked();
  1082. }
  1083. }
  1084. const XMLElement* XMLNode::ToElementWithName(const char* name) const
  1085. {
  1086. const XMLElement* element = this->ToElement();
  1087. if (element == 0)
  1088. {
  1089. return 0;
  1090. }
  1091. if (name == 0)
  1092. {
  1093. return element;
  1094. }
  1095. if (XMLUtil::StringEqual(element->Name(), name))
  1096. {
  1097. return element;
  1098. }
  1099. return 0;
  1100. }
  1101. // --------- XMLText ---------- //
  1102. char* XMLText::ParseDeep(char* p, StrPair*, int* curLineNumPtr)
  1103. {
  1104. if (this->CData())
  1105. {
  1106. p = _value.ParseText(p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr);
  1107. if (!p)
  1108. {
  1109. _document->SetError(XML_ERROR_PARSING_CDATA, _parseLineNum, 0);
  1110. }
  1111. return p;
  1112. }
  1113. else
  1114. {
  1115. int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES;
  1116. if (_document->WhitespaceMode() == COLLAPSE_WHITESPACE)
  1117. {
  1118. flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING;
  1119. }
  1120. p = _value.ParseText(p, "<", flags, curLineNumPtr);
  1121. if (p && *p)
  1122. {
  1123. return p - 1;
  1124. }
  1125. if (!p)
  1126. {
  1127. _document->SetError(XML_ERROR_PARSING_TEXT, _parseLineNum, 0);
  1128. }
  1129. }
  1130. return 0;
  1131. }
  1132. XMLNode* XMLText::ShallowClone(XMLDocument* doc) const
  1133. {
  1134. if (!doc)
  1135. {
  1136. doc = _document;
  1137. }
  1138. XMLText* text = doc->NewText(Value()); // fixme: this will always allocate memory. Intern?
  1139. text->SetCData(this->CData());
  1140. return text;
  1141. }
  1142. bool XMLText::ShallowEqual(const XMLNode* compare) const
  1143. {
  1144. TIXMLASSERT(compare);
  1145. const XMLText* text = compare->ToText();
  1146. return (text && XMLUtil::StringEqual(text->Value(), Value()));
  1147. }
  1148. bool XMLText::Accept(XMLVisitor* visitor) const
  1149. {
  1150. TIXMLASSERT(visitor);
  1151. return visitor->Visit(*this);
  1152. }
  1153. // --------- XMLComment ---------- //
  1154. XMLComment::XMLComment(XMLDocument* doc) : XMLNode(doc)
  1155. {
  1156. }
  1157. XMLComment::~XMLComment()
  1158. {
  1159. }
  1160. char* XMLComment::ParseDeep(char* p, StrPair*, int* curLineNumPtr)
  1161. {
  1162. // Comment parses as text.
  1163. p = _value.ParseText(p, "-->", StrPair::COMMENT, curLineNumPtr);
  1164. if (p == 0)
  1165. {
  1166. _document->SetError(XML_ERROR_PARSING_COMMENT, _parseLineNum, 0);
  1167. }
  1168. return p;
  1169. }
  1170. XMLNode* XMLComment::ShallowClone(XMLDocument* doc) const
  1171. {
  1172. if (!doc)
  1173. {
  1174. doc = _document;
  1175. }
  1176. XMLComment* comment = doc->NewComment(Value()); // fixme: this will always allocate memory. Intern?
  1177. return comment;
  1178. }
  1179. bool XMLComment::ShallowEqual(const XMLNode* compare) const
  1180. {
  1181. TIXMLASSERT(compare);
  1182. const XMLComment* comment = compare->ToComment();
  1183. return (comment && XMLUtil::StringEqual(comment->Value(), Value()));
  1184. }
  1185. bool XMLComment::Accept(XMLVisitor* visitor) const
  1186. {
  1187. TIXMLASSERT(visitor);
  1188. return visitor->Visit(*this);
  1189. }
  1190. // --------- XMLDeclaration ---------- //
  1191. XMLDeclaration::XMLDeclaration(XMLDocument* doc) : XMLNode(doc)
  1192. {
  1193. }
  1194. XMLDeclaration::~XMLDeclaration()
  1195. {
  1196. //printf( "~XMLDeclaration\n" );
  1197. }
  1198. char* XMLDeclaration::ParseDeep(char* p, StrPair*, int* curLineNumPtr)
  1199. {
  1200. // Declaration parses as text.
  1201. p = _value.ParseText(p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr);
  1202. if (p == 0)
  1203. {
  1204. _document->SetError(XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0);
  1205. }
  1206. return p;
  1207. }
  1208. XMLNode* XMLDeclaration::ShallowClone(XMLDocument* doc) const
  1209. {
  1210. if (!doc)
  1211. {
  1212. doc = _document;
  1213. }
  1214. XMLDeclaration* dec = doc->NewDeclaration(Value()); // fixme: this will always allocate memory. Intern?
  1215. return dec;
  1216. }
  1217. bool XMLDeclaration::ShallowEqual(const XMLNode* compare) const
  1218. {
  1219. TIXMLASSERT(compare);
  1220. const XMLDeclaration* declaration = compare->ToDeclaration();
  1221. return (declaration && XMLUtil::StringEqual(declaration->Value(), Value()));
  1222. }
  1223. bool XMLDeclaration::Accept(XMLVisitor* visitor) const
  1224. {
  1225. TIXMLASSERT(visitor);
  1226. return visitor->Visit(*this);
  1227. }
  1228. // --------- XMLUnknown ---------- //
  1229. XMLUnknown::XMLUnknown(XMLDocument* doc) : XMLNode(doc)
  1230. {
  1231. }
  1232. XMLUnknown::~XMLUnknown()
  1233. {
  1234. }
  1235. char* XMLUnknown::ParseDeep(char* p, StrPair*, int* curLineNumPtr)
  1236. {
  1237. // Unknown parses as text.
  1238. p = _value.ParseText(p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr);
  1239. if (!p)
  1240. {
  1241. _document->SetError(XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0);
  1242. }
  1243. return p;
  1244. }
  1245. XMLNode* XMLUnknown::ShallowClone(XMLDocument* doc) const
  1246. {
  1247. if (!doc)
  1248. {
  1249. doc = _document;
  1250. }
  1251. XMLUnknown* text = doc->NewUnknown(Value()); // fixme: this will always allocate memory. Intern?
  1252. return text;
  1253. }
  1254. bool XMLUnknown::ShallowEqual(const XMLNode* compare) const
  1255. {
  1256. TIXMLASSERT(compare);
  1257. const XMLUnknown* unknown = compare->ToUnknown();
  1258. return (unknown && XMLUtil::StringEqual(unknown->Value(), Value()));
  1259. }
  1260. bool XMLUnknown::Accept(XMLVisitor* visitor) const
  1261. {
  1262. TIXMLASSERT(visitor);
  1263. return visitor->Visit(*this);
  1264. }
  1265. // --------- XMLAttribute ---------- //
  1266. const char* XMLAttribute::Name() const
  1267. {
  1268. return _name.GetStr();
  1269. }
  1270. const char* XMLAttribute::Value() const
  1271. {
  1272. return _value.GetStr();
  1273. }
  1274. char* XMLAttribute::ParseDeep(char* p, bool processEntities, int* curLineNumPtr)
  1275. {
  1276. // Parse using the name rules: bug fix, was using ParseText before
  1277. p = _name.ParseName(p);
  1278. if (!p || !*p)
  1279. {
  1280. return 0;
  1281. }
  1282. // Skip white space before =
  1283. p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr);
  1284. if (*p != '=')
  1285. {
  1286. return 0;
  1287. }
  1288. ++p; // move up to opening quote
  1289. p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr);
  1290. if (*p != '\"' && *p != '\'')
  1291. {
  1292. return 0;
  1293. }
  1294. char endTag[2] = {*p, 0};
  1295. ++p; // move past opening quote
  1296. p = _value.ParseText(p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr);
  1297. return p;
  1298. }
  1299. void XMLAttribute::SetName(const char* n)
  1300. {
  1301. _name.SetStr(n);
  1302. }
  1303. XMLError XMLAttribute::QueryIntValue(int* value) const
  1304. {
  1305. if (XMLUtil::ToInt(Value(), value))
  1306. {
  1307. return XML_SUCCESS;
  1308. }
  1309. return XML_WRONG_ATTRIBUTE_TYPE;
  1310. }
  1311. XMLError XMLAttribute::QueryUnsignedValue(unsigned int* value) const
  1312. {
  1313. if (XMLUtil::ToUnsigned(Value(), value))
  1314. {
  1315. return XML_SUCCESS;
  1316. }
  1317. return XML_WRONG_ATTRIBUTE_TYPE;
  1318. }
  1319. XMLError XMLAttribute::QueryInt64Value(xml_Int64a_t* value) const
  1320. {
  1321. if (XMLUtil::ToInt64(Value(), value))
  1322. {
  1323. return XML_SUCCESS;
  1324. }
  1325. return XML_WRONG_ATTRIBUTE_TYPE;
  1326. }
  1327. XMLError XMLAttribute::QueryBoolValue(bool* value) const
  1328. {
  1329. if (XMLUtil::ToBool(Value(), value))
  1330. {
  1331. return XML_SUCCESS;
  1332. }
  1333. return XML_WRONG_ATTRIBUTE_TYPE;
  1334. }
  1335. XMLError XMLAttribute::QueryFloatValue(float* value) const
  1336. {
  1337. if (XMLUtil::ToFloat(Value(), value))
  1338. {
  1339. return XML_SUCCESS;
  1340. }
  1341. return XML_WRONG_ATTRIBUTE_TYPE;
  1342. }
  1343. XMLError XMLAttribute::QueryDoubleValue(double* value) const
  1344. {
  1345. if (XMLUtil::ToDouble(Value(), value))
  1346. {
  1347. return XML_SUCCESS;
  1348. }
  1349. return XML_WRONG_ATTRIBUTE_TYPE;
  1350. }
  1351. void XMLAttribute::SetAttribute(const char* v)
  1352. {
  1353. _value.SetStr(v);
  1354. }
  1355. void XMLAttribute::SetAttribute(int v)
  1356. {
  1357. char buf[BUF_SIZE];
  1358. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1359. _value.SetStr(buf);
  1360. }
  1361. void XMLAttribute::SetAttribute(unsigned v)
  1362. {
  1363. char buf[BUF_SIZE];
  1364. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1365. _value.SetStr(buf);
  1366. }
  1367. void XMLAttribute::SetAttribute(xml_Int64a_t v)
  1368. {
  1369. char buf[BUF_SIZE];
  1370. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1371. _value.SetStr(buf);
  1372. }
  1373. void XMLAttribute::SetAttribute(bool v)
  1374. {
  1375. char buf[BUF_SIZE];
  1376. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1377. _value.SetStr(buf);
  1378. }
  1379. void XMLAttribute::SetAttribute(double v)
  1380. {
  1381. char buf[BUF_SIZE];
  1382. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1383. _value.SetStr(buf);
  1384. }
  1385. void XMLAttribute::SetAttribute(float v)
  1386. {
  1387. char buf[BUF_SIZE];
  1388. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1389. _value.SetStr(buf);
  1390. }
  1391. // --------- XMLElement ---------- //
  1392. XMLElement::XMLElement(XMLDocument* doc) : XMLNode(doc),
  1393. _closingType(OPEN),
  1394. _rootAttribute(0)
  1395. {
  1396. }
  1397. XMLElement::~XMLElement()
  1398. {
  1399. while (_rootAttribute)
  1400. {
  1401. XMLAttribute* next = _rootAttribute->_next;
  1402. DeleteAttribute(_rootAttribute);
  1403. _rootAttribute = next;
  1404. }
  1405. }
  1406. const XMLAttribute* XMLElement::FindAttribute(const char* name) const
  1407. {
  1408. for (XMLAttribute* a = _rootAttribute; a; a = a->_next)
  1409. {
  1410. if (XMLUtil::StringEqual(a->Name(), name))
  1411. {
  1412. return a;
  1413. }
  1414. }
  1415. return 0;
  1416. }
  1417. const char* XMLElement::Attribute(const char* name, const char* value) const
  1418. {
  1419. const XMLAttribute* a = FindAttribute(name);
  1420. if (!a)
  1421. {
  1422. return 0;
  1423. }
  1424. if (!value || XMLUtil::StringEqual(a->Value(), value))
  1425. {
  1426. return a->Value();
  1427. }
  1428. return 0;
  1429. }
  1430. int XMLElement::IntAttribute(const char* name, int defaultValue) const
  1431. {
  1432. int i = defaultValue;
  1433. QueryIntAttribute(name, &i);
  1434. return i;
  1435. }
  1436. unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const
  1437. {
  1438. unsigned i = defaultValue;
  1439. QueryUnsignedAttribute(name, &i);
  1440. return i;
  1441. }
  1442. xml_Int64a_t XMLElement::Int64Attribute(const char* name, xml_Int64a_t defaultValue) const
  1443. {
  1444. xml_Int64a_t i = defaultValue;
  1445. QueryInt64Attribute(name, &i);
  1446. return i;
  1447. }
  1448. bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const
  1449. {
  1450. bool b = defaultValue;
  1451. QueryBoolAttribute(name, &b);
  1452. return b;
  1453. }
  1454. double XMLElement::DoubleAttribute(const char* name, double defaultValue) const
  1455. {
  1456. double d = defaultValue;
  1457. QueryDoubleAttribute(name, &d);
  1458. return d;
  1459. }
  1460. float XMLElement::FloatAttribute(const char* name, float defaultValue) const
  1461. {
  1462. float f = defaultValue;
  1463. QueryFloatAttribute(name, &f);
  1464. return f;
  1465. }
  1466. const char* XMLElement::GetText() const
  1467. {
  1468. if (FirstChild() && FirstChild()->ToText())
  1469. {
  1470. return FirstChild()->Value();
  1471. }
  1472. return 0;
  1473. }
  1474. void XMLElement::SetText(const char* inText)
  1475. {
  1476. if (FirstChild() && FirstChild()->ToText())
  1477. FirstChild()->SetValue(inText);
  1478. else
  1479. {
  1480. XMLText* theText = GetDocument()->NewText(inText);
  1481. InsertFirstChild(theText);
  1482. }
  1483. }
  1484. void XMLElement::SetText(int v)
  1485. {
  1486. char buf[BUF_SIZE];
  1487. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1488. SetText(buf);
  1489. }
  1490. void XMLElement::SetText(unsigned v)
  1491. {
  1492. char buf[BUF_SIZE];
  1493. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1494. SetText(buf);
  1495. }
  1496. void XMLElement::SetText(xml_Int64a_t v)
  1497. {
  1498. char buf[BUF_SIZE];
  1499. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1500. SetText(buf);
  1501. }
  1502. void XMLElement::SetText(bool v)
  1503. {
  1504. char buf[BUF_SIZE];
  1505. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1506. SetText(buf);
  1507. }
  1508. void XMLElement::SetText(float v)
  1509. {
  1510. char buf[BUF_SIZE];
  1511. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1512. SetText(buf);
  1513. }
  1514. void XMLElement::SetText(double v)
  1515. {
  1516. char buf[BUF_SIZE];
  1517. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1518. SetText(buf);
  1519. }
  1520. XMLError XMLElement::QueryIntText(int* ival) const
  1521. {
  1522. if (FirstChild() && FirstChild()->ToText())
  1523. {
  1524. const char* t = FirstChild()->Value();
  1525. if (XMLUtil::ToInt(t, ival))
  1526. {
  1527. return XML_SUCCESS;
  1528. }
  1529. return XML_CAN_NOT_CONVERT_TEXT;
  1530. }
  1531. return XML_NO_TEXT_NODE;
  1532. }
  1533. XMLError XMLElement::QueryUnsignedText(unsigned* uval) const
  1534. {
  1535. if (FirstChild() && FirstChild()->ToText())
  1536. {
  1537. const char* t = FirstChild()->Value();
  1538. if (XMLUtil::ToUnsigned(t, uval))
  1539. {
  1540. return XML_SUCCESS;
  1541. }
  1542. return XML_CAN_NOT_CONVERT_TEXT;
  1543. }
  1544. return XML_NO_TEXT_NODE;
  1545. }
  1546. XMLError XMLElement::QueryInt64Text(xml_Int64a_t* ival) const
  1547. {
  1548. if (FirstChild() && FirstChild()->ToText())
  1549. {
  1550. const char* t = FirstChild()->Value();
  1551. if (XMLUtil::ToInt64(t, ival))
  1552. {
  1553. return XML_SUCCESS;
  1554. }
  1555. return XML_CAN_NOT_CONVERT_TEXT;
  1556. }
  1557. return XML_NO_TEXT_NODE;
  1558. }
  1559. XMLError XMLElement::QueryBoolText(bool* bval) const
  1560. {
  1561. if (FirstChild() && FirstChild()->ToText())
  1562. {
  1563. const char* t = FirstChild()->Value();
  1564. if (XMLUtil::ToBool(t, bval))
  1565. {
  1566. return XML_SUCCESS;
  1567. }
  1568. return XML_CAN_NOT_CONVERT_TEXT;
  1569. }
  1570. return XML_NO_TEXT_NODE;
  1571. }
  1572. XMLError XMLElement::QueryDoubleText(double* dval) const
  1573. {
  1574. if (FirstChild() && FirstChild()->ToText())
  1575. {
  1576. const char* t = FirstChild()->Value();
  1577. if (XMLUtil::ToDouble(t, dval))
  1578. {
  1579. return XML_SUCCESS;
  1580. }
  1581. return XML_CAN_NOT_CONVERT_TEXT;
  1582. }
  1583. return XML_NO_TEXT_NODE;
  1584. }
  1585. XMLError XMLElement::QueryFloatText(float* fval) const
  1586. {
  1587. if (FirstChild() && FirstChild()->ToText())
  1588. {
  1589. const char* t = FirstChild()->Value();
  1590. if (XMLUtil::ToFloat(t, fval))
  1591. {
  1592. return XML_SUCCESS;
  1593. }
  1594. return XML_CAN_NOT_CONVERT_TEXT;
  1595. }
  1596. return XML_NO_TEXT_NODE;
  1597. }
  1598. int XMLElement::IntText(int defaultValue) const
  1599. {
  1600. int i = defaultValue;
  1601. QueryIntText(&i);
  1602. return i;
  1603. }
  1604. unsigned XMLElement::UnsignedText(unsigned defaultValue) const
  1605. {
  1606. unsigned i = defaultValue;
  1607. QueryUnsignedText(&i);
  1608. return i;
  1609. }
  1610. xml_Int64a_t XMLElement::Int64Text(xml_Int64a_t defaultValue) const
  1611. {
  1612. xml_Int64a_t i = defaultValue;
  1613. QueryInt64Text(&i);
  1614. return i;
  1615. }
  1616. bool XMLElement::BoolText(bool defaultValue) const
  1617. {
  1618. bool b = defaultValue;
  1619. QueryBoolText(&b);
  1620. return b;
  1621. }
  1622. double XMLElement::DoubleText(double defaultValue) const
  1623. {
  1624. double d = defaultValue;
  1625. QueryDoubleText(&d);
  1626. return d;
  1627. }
  1628. float XMLElement::FloatText(float defaultValue) const
  1629. {
  1630. float f = defaultValue;
  1631. QueryFloatText(&f);
  1632. return f;
  1633. }
  1634. XMLAttribute* XMLElement::FindOrCreateAttribute(const char* name)
  1635. {
  1636. XMLAttribute* last = 0;
  1637. XMLAttribute* attrib = 0;
  1638. for (attrib = _rootAttribute;
  1639. attrib;
  1640. last = attrib, attrib = attrib->_next)
  1641. {
  1642. if (XMLUtil::StringEqual(attrib->Name(), name))
  1643. {
  1644. break;
  1645. }
  1646. }
  1647. if (!attrib)
  1648. {
  1649. attrib = CreateAttribute();
  1650. TIXMLASSERT(attrib);
  1651. if (last)
  1652. {
  1653. TIXMLASSERT(last->_next == 0);
  1654. last->_next = attrib;
  1655. }
  1656. else
  1657. {
  1658. TIXMLASSERT(_rootAttribute == 0);
  1659. _rootAttribute = attrib;
  1660. }
  1661. attrib->SetName(name);
  1662. }
  1663. return attrib;
  1664. }
  1665. void XMLElement::DeleteAttribute(const char* name)
  1666. {
  1667. XMLAttribute* prev = 0;
  1668. for (XMLAttribute* a = _rootAttribute; a; a = a->_next)
  1669. {
  1670. if (XMLUtil::StringEqual(name, a->Name()))
  1671. {
  1672. if (prev)
  1673. {
  1674. prev->_next = a->_next;
  1675. }
  1676. else
  1677. {
  1678. _rootAttribute = a->_next;
  1679. }
  1680. DeleteAttribute(a);
  1681. break;
  1682. }
  1683. prev = a;
  1684. }
  1685. }
  1686. char* XMLElement::ParseAttributes(char* p, int* curLineNumPtr)
  1687. {
  1688. XMLAttribute* prevAttribute = 0;
  1689. // Read the attributes.
  1690. while (p)
  1691. {
  1692. p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr);
  1693. if (!(*p))
  1694. {
  1695. _document->SetError(XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name());
  1696. return 0;
  1697. }
  1698. // attribute.
  1699. if (XMLUtil::IsNameStartChar(*p))
  1700. {
  1701. XMLAttribute* attrib = CreateAttribute();
  1702. TIXMLASSERT(attrib);
  1703. attrib->_parseLineNum = _document->_parseCurLineNum;
  1704. int attrLineNum = attrib->_parseLineNum;
  1705. p = attrib->ParseDeep(p, _document->ProcessEntities(), curLineNumPtr);
  1706. if (!p || Attribute(attrib->Name()))
  1707. {
  1708. DeleteAttribute(attrib);
  1709. _document->SetError(XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name());
  1710. return 0;
  1711. }
  1712. // There is a minor bug here: if the attribute in the source xml
  1713. // document is duplicated, it will not be detected and the
  1714. // attribute will be doubly added. However, tracking the 'prevAttribute'
  1715. // avoids re-scanning the attribute list. Preferring performance for
  1716. // now, may reconsider in the future.
  1717. if (prevAttribute)
  1718. {
  1719. TIXMLASSERT(prevAttribute->_next == 0);
  1720. prevAttribute->_next = attrib;
  1721. }
  1722. else
  1723. {
  1724. TIXMLASSERT(_rootAttribute == 0);
  1725. _rootAttribute = attrib;
  1726. }
  1727. prevAttribute = attrib;
  1728. }
  1729. // end of the tag
  1730. else if (*p == '>')
  1731. {
  1732. ++p;
  1733. break;
  1734. }
  1735. // end of the tag
  1736. else if (*p == '/' && *(p + 1) == '>')
  1737. {
  1738. _closingType = CLOSED;
  1739. return p + 2; // done; sealed element.
  1740. }
  1741. else
  1742. {
  1743. _document->SetError(XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0);
  1744. return 0;
  1745. }
  1746. }
  1747. return p;
  1748. }
  1749. void XMLElement::DeleteAttribute(XMLAttribute* attribute)
  1750. {
  1751. if (attribute == 0)
  1752. {
  1753. return;
  1754. }
  1755. MemPool* pool = attribute->_memPool;
  1756. attribute->~XMLAttribute();
  1757. pool->Free(attribute);
  1758. }
  1759. XMLAttribute* XMLElement::CreateAttribute()
  1760. {
  1761. TIXMLASSERT(sizeof(XMLAttribute) == _document->_attributePool.ItemSize());
  1762. XMLAttribute* attrib = new (_document->_attributePool.Alloc()) XMLAttribute();
  1763. TIXMLASSERT(attrib);
  1764. attrib->_memPool = &_document->_attributePool;
  1765. attrib->_memPool->SetTracked();
  1766. return attrib;
  1767. }
  1768. //
  1769. // <ele></ele>
  1770. // <ele>foo<b>bar</b></ele>
  1771. //
  1772. char* XMLElement::ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr)
  1773. {
  1774. // Read the element name.
  1775. p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr);
  1776. // The closing element is the </element> form. It is
  1777. // parsed just like a regular element then deleted from
  1778. // the DOM.
  1779. if (*p == '/')
  1780. {
  1781. _closingType = CLOSING;
  1782. ++p;
  1783. }
  1784. p = _value.ParseName(p);
  1785. if (_value.Empty())
  1786. {
  1787. return 0;
  1788. }
  1789. p = ParseAttributes(p, curLineNumPtr);
  1790. if (!p || !*p || _closingType != OPEN)
  1791. {
  1792. return p;
  1793. }
  1794. p = XMLNode::ParseDeep(p, parentEndTag, curLineNumPtr);
  1795. return p;
  1796. }
  1797. XMLNode* XMLElement::ShallowClone(XMLDocument* doc) const
  1798. {
  1799. if (!doc)
  1800. {
  1801. doc = _document;
  1802. }
  1803. XMLElement* element = doc->NewElement(Value()); // fixme: this will always allocate memory. Intern?
  1804. for (const XMLAttribute* a = FirstAttribute(); a; a = a->Next())
  1805. {
  1806. element->SetAttribute(a->Name(), a->Value()); // fixme: this will always allocate memory. Intern?
  1807. }
  1808. return element;
  1809. }
  1810. bool XMLElement::ShallowEqual(const XMLNode* compare) const
  1811. {
  1812. TIXMLASSERT(compare);
  1813. const XMLElement* other = compare->ToElement();
  1814. if (other && XMLUtil::StringEqual(other->Name(), Name()))
  1815. {
  1816. const XMLAttribute* a = FirstAttribute();
  1817. const XMLAttribute* b = other->FirstAttribute();
  1818. while (a && b)
  1819. {
  1820. if (!XMLUtil::StringEqual(a->Value(), b->Value()))
  1821. {
  1822. return false;
  1823. }
  1824. a = a->Next();
  1825. b = b->Next();
  1826. }
  1827. if (a || b)
  1828. {
  1829. // different count
  1830. return false;
  1831. }
  1832. return true;
  1833. }
  1834. return false;
  1835. }
  1836. bool XMLElement::Accept(XMLVisitor* visitor) const
  1837. {
  1838. TIXMLASSERT(visitor);
  1839. if (visitor->VisitEnter(*this, _rootAttribute))
  1840. {
  1841. for (const XMLNode* node = FirstChild(); node; node = node->NextSibling())
  1842. {
  1843. if (!node->Accept(visitor))
  1844. {
  1845. break;
  1846. }
  1847. }
  1848. }
  1849. return visitor->VisitExit(*this);
  1850. }
  1851. // --------- XMLDocument ----------- //
  1852. // Warning: List must match 'enum XMLError'
  1853. const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = {
  1854. "XML_SUCCESS",
  1855. "XML_NO_ATTRIBUTE",
  1856. "XML_WRONG_ATTRIBUTE_TYPE",
  1857. "XML_ERROR_FILE_NOT_FOUND",
  1858. "XML_ERROR_FILE_COULD_NOT_BE_OPENED",
  1859. "XML_ERROR_FILE_READ_ERROR",
  1860. "UNUSED_XML_ERROR_ELEMENT_MISMATCH",
  1861. "XML_ERROR_PARSING_ELEMENT",
  1862. "XML_ERROR_PARSING_ATTRIBUTE",
  1863. "UNUSED_XML_ERROR_IDENTIFYING_TAG",
  1864. "XML_ERROR_PARSING_TEXT",
  1865. "XML_ERROR_PARSING_CDATA",
  1866. "XML_ERROR_PARSING_COMMENT",
  1867. "XML_ERROR_PARSING_DECLARATION",
  1868. "XML_ERROR_PARSING_UNKNOWN",
  1869. "XML_ERROR_EMPTY_DOCUMENT",
  1870. "XML_ERROR_MISMATCHED_ELEMENT",
  1871. "XML_ERROR_PARSING",
  1872. "XML_CAN_NOT_CONVERT_TEXT",
  1873. "XML_NO_TEXT_NODE",
  1874. "XML_ELEMENT_DEPTH_EXCEEDED"};
  1875. XMLDocument::XMLDocument(bool processEntities, Whitespace whitespaceMode) : XMLNode(0),
  1876. _writeBOM(false),
  1877. _processEntities(processEntities),
  1878. _errorID(XML_SUCCESS),
  1879. _whitespaceMode(whitespaceMode),
  1880. _errorStr(),
  1881. _errorLineNum(0),
  1882. _charBuffer(0),
  1883. _parseCurLineNum(0),
  1884. _parsingDepth(0),
  1885. _unlinked(),
  1886. _elementPool(),
  1887. _attributePool(),
  1888. _textPool(),
  1889. _commentPool()
  1890. {
  1891. // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+)
  1892. _document = this;
  1893. }
  1894. XMLDocument::~XMLDocument()
  1895. {
  1896. Clear();
  1897. }
  1898. void XMLDocument::MarkInUse(XMLNode* node)
  1899. {
  1900. TIXMLASSERT(node);
  1901. TIXMLASSERT(node->_parent == 0);
  1902. for (int i = 0; i < _unlinked.Size(); ++i)
  1903. {
  1904. if (node == _unlinked[i])
  1905. {
  1906. _unlinked.SwapRemove(i);
  1907. break;
  1908. }
  1909. }
  1910. }
  1911. void XMLDocument::Clear()
  1912. {
  1913. DeleteChildren();
  1914. while (_unlinked.Size())
  1915. {
  1916. DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete.
  1917. }
  1918. #ifdef TINYXML2_DEBUG
  1919. const bool hadError = Error();
  1920. #endif
  1921. ClearError();
  1922. delete[] _charBuffer;
  1923. _charBuffer = 0;
  1924. _parsingDepth = 0;
  1925. #if 0
  1926. _textPool.Trace( "text" );
  1927. _elementPool.Trace( "element" );
  1928. _commentPool.Trace( "comment" );
  1929. _attributePool.Trace( "attribute" );
  1930. #endif
  1931. #ifdef TINYXML2_DEBUG
  1932. if (!hadError)
  1933. {
  1934. TIXMLASSERT(_elementPool.CurrentAllocs() == _elementPool.Untracked());
  1935. TIXMLASSERT(_attributePool.CurrentAllocs() == _attributePool.Untracked());
  1936. TIXMLASSERT(_textPool.CurrentAllocs() == _textPool.Untracked());
  1937. TIXMLASSERT(_commentPool.CurrentAllocs() == _commentPool.Untracked());
  1938. }
  1939. #endif
  1940. }
  1941. void XMLDocument::DeepCopy(XMLDocument* target) const
  1942. {
  1943. TIXMLASSERT(target);
  1944. if (target == this)
  1945. {
  1946. return; // technically success - a no-op.
  1947. }
  1948. target->Clear();
  1949. for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling())
  1950. {
  1951. target->InsertEndChild(node->DeepClone(target));
  1952. }
  1953. }
  1954. XMLElement* XMLDocument::NewElement(const char* name)
  1955. {
  1956. XMLElement* ele = CreateUnlinkedNode<XMLElement>(_elementPool);
  1957. ele->SetName(name);
  1958. return ele;
  1959. }
  1960. XMLComment* XMLDocument::NewComment(const char* str)
  1961. {
  1962. XMLComment* comment = CreateUnlinkedNode<XMLComment>(_commentPool);
  1963. comment->SetValue(str);
  1964. return comment;
  1965. }
  1966. XMLText* XMLDocument::NewText(const char* str)
  1967. {
  1968. XMLText* text = CreateUnlinkedNode<XMLText>(_textPool);
  1969. text->SetValue(str);
  1970. return text;
  1971. }
  1972. XMLDeclaration* XMLDocument::NewDeclaration(const char* str)
  1973. {
  1974. XMLDeclaration* dec = CreateUnlinkedNode<XMLDeclaration>(_commentPool);
  1975. dec->SetValue(str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"");
  1976. return dec;
  1977. }
  1978. XMLUnknown* XMLDocument::NewUnknown(const char* str)
  1979. {
  1980. XMLUnknown* unk = CreateUnlinkedNode<XMLUnknown>(_commentPool);
  1981. unk->SetValue(str);
  1982. return unk;
  1983. }
  1984. static FILE* callfopen(const char* filepath, const char* mode)
  1985. {
  1986. TIXMLASSERT(filepath);
  1987. TIXMLASSERT(mode);
  1988. #if defined(_MSC_VER) && (_MSC_VER >= 1400) && (!defined WINCE)
  1989. FILE* fp = 0;
  1990. errno_t err = fopen_s(&fp, filepath, mode);
  1991. if (err)
  1992. {
  1993. return 0;
  1994. }
  1995. #else
  1996. FILE* fp = fopen(filepath, mode);
  1997. #endif
  1998. return fp;
  1999. }
  2000. void XMLDocument::DeleteNode(XMLNode* node)
  2001. {
  2002. TIXMLASSERT(node);
  2003. TIXMLASSERT(node->_document == this);
  2004. if (node->_parent)
  2005. {
  2006. node->_parent->DeleteChild(node);
  2007. }
  2008. else
  2009. {
  2010. // Isn't in the tree.
  2011. // Use the parent delete.
  2012. // Also, we need to mark it tracked: we 'know'
  2013. // it was never used.
  2014. node->_memPool->SetTracked();
  2015. // Call the static XMLNode version:
  2016. XMLNode::DeleteNode(node);
  2017. }
  2018. }
  2019. XMLError XMLDocument::LoadFile(const char* filename)
  2020. {
  2021. if (!filename)
  2022. {
  2023. TIXMLASSERT(false);
  2024. SetError(XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=<null>");
  2025. return _errorID;
  2026. }
  2027. Clear();
  2028. FILE* fp = callfopen(filename, "rb");
  2029. if (!fp)
  2030. {
  2031. SetError(XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename);
  2032. return _errorID;
  2033. }
  2034. LoadFile(fp);
  2035. fclose(fp);
  2036. return _errorID;
  2037. }
  2038. // This is likely overengineered template art to have a check that unsigned long value incremented
  2039. // by one still fits into size_t. If size_t type is larger than unsigned long type
  2040. // (x86_64-w64-mingw32 target) then the check is redundant and gcc and clang emit
  2041. // -Wtype-limits warning. This piece makes the compiler select code with a check when a check
  2042. // is useful and code with no check when a check is redundant depending on how size_t and unsigned long
  2043. // types sizes relate to each other.
  2044. template <bool = (sizeof(unsigned long) >= sizeof(size_t))>
  2045. struct LongFitsIntoSizeTMinusOne
  2046. {
  2047. static bool Fits(unsigned long value)
  2048. {
  2049. return value < (size_t)-1;
  2050. }
  2051. };
  2052. template <>
  2053. struct LongFitsIntoSizeTMinusOne<false>
  2054. {
  2055. static bool Fits(unsigned long)
  2056. {
  2057. return true;
  2058. }
  2059. };
  2060. XMLError XMLDocument::LoadFile(FILE* fp)
  2061. {
  2062. Clear();
  2063. fseek(fp, 0, SEEK_SET);
  2064. if (fgetc(fp) == EOF && ferror(fp) != 0)
  2065. {
  2066. SetError(XML_ERROR_FILE_READ_ERROR, 0, 0);
  2067. return _errorID;
  2068. }
  2069. fseek(fp, 0, SEEK_END);
  2070. const long filelength = ftell(fp);
  2071. fseek(fp, 0, SEEK_SET);
  2072. if (filelength == -1L)
  2073. {
  2074. SetError(XML_ERROR_FILE_READ_ERROR, 0, 0);
  2075. return _errorID;
  2076. }
  2077. TIXMLASSERT(filelength >= 0);
  2078. if (!LongFitsIntoSizeTMinusOne<>::Fits(filelength))
  2079. {
  2080. // Cannot handle files which won't fit in buffer together with null terminator
  2081. SetError(XML_ERROR_FILE_READ_ERROR, 0, 0);
  2082. return _errorID;
  2083. }
  2084. if (filelength == 0)
  2085. {
  2086. SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0);
  2087. return _errorID;
  2088. }
  2089. const size_t size = filelength;
  2090. TIXMLASSERT(_charBuffer == 0);
  2091. _charBuffer = new char[size + 1];
  2092. size_t read = fread(_charBuffer, 1, size, fp);
  2093. if (read != size)
  2094. {
  2095. SetError(XML_ERROR_FILE_READ_ERROR, 0, 0);
  2096. return _errorID;
  2097. }
  2098. _charBuffer[size] = 0;
  2099. Parse();
  2100. return _errorID;
  2101. }
  2102. XMLError XMLDocument::SaveFile(const char* filename, bool compact)
  2103. {
  2104. if (!filename)
  2105. {
  2106. TIXMLASSERT(false);
  2107. SetError(XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=<null>");
  2108. return _errorID;
  2109. }
  2110. FILE* fp = callfopen(filename, "w");
  2111. if (!fp)
  2112. {
  2113. SetError(XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename);
  2114. return _errorID;
  2115. }
  2116. SaveFile(fp, compact);
  2117. fclose(fp);
  2118. return _errorID;
  2119. }
  2120. XMLError XMLDocument::SaveFile(FILE* fp, bool compact)
  2121. {
  2122. // Clear any error from the last save, otherwise it will get reported
  2123. // for *this* call.
  2124. ClearError();
  2125. XMLPrinter stream(fp, compact);
  2126. Print(&stream);
  2127. return _errorID;
  2128. }
  2129. XMLError XMLDocument::Parse(const char* p, size_t len)
  2130. {
  2131. Clear();
  2132. if (len == 0 || !p || !*p)
  2133. {
  2134. SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0);
  2135. return _errorID;
  2136. }
  2137. if (len == (size_t)(-1))
  2138. {
  2139. len = strlen(p);
  2140. }
  2141. TIXMLASSERT(_charBuffer == 0);
  2142. _charBuffer = new char[len + 1];
  2143. memcpy(_charBuffer, p, len);
  2144. _charBuffer[len] = 0;
  2145. Parse();
  2146. if (Error())
  2147. {
  2148. // clean up now essentially dangling memory.
  2149. // and the parse fail can put objects in the
  2150. // pools that are dead and inaccessible.
  2151. DeleteChildren();
  2152. _elementPool.Clear();
  2153. _attributePool.Clear();
  2154. _textPool.Clear();
  2155. _commentPool.Clear();
  2156. }
  2157. return _errorID;
  2158. }
  2159. void XMLDocument::Print(XMLPrinter* streamer) const
  2160. {
  2161. if (streamer)
  2162. {
  2163. Accept(streamer);
  2164. }
  2165. else
  2166. {
  2167. XMLPrinter stdoutStreamer(stdout);
  2168. Accept(&stdoutStreamer);
  2169. }
  2170. }
  2171. void XMLDocument::SetError(XMLError error, int lineNum, const char* format, ...)
  2172. {
  2173. TIXMLASSERT(error >= 0 && error < XML_ERROR_COUNT);
  2174. _errorID = error;
  2175. _errorLineNum = lineNum;
  2176. _errorStr.Reset();
  2177. size_t BUFFER_SIZE = 1000;
  2178. char* buffer = new char[BUFFER_SIZE];
  2179. TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum);
  2180. if (format)
  2181. {
  2182. size_t len = strlen(buffer);
  2183. TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": ");
  2184. len = strlen(buffer);
  2185. va_list va;
  2186. va_start(va, format);
  2187. TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va);
  2188. va_end(va);
  2189. }
  2190. _errorStr.SetStr(buffer);
  2191. delete[] buffer;
  2192. }
  2193. /*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID)
  2194. {
  2195. TIXMLASSERT(errorID >= 0 && errorID < XML_ERROR_COUNT);
  2196. const char* errorName = _errorNames[errorID];
  2197. TIXMLASSERT(errorName && errorName[0]);
  2198. return errorName;
  2199. }
  2200. const char* XMLDocument::ErrorStr() const
  2201. {
  2202. return _errorStr.Empty() ? "" : _errorStr.GetStr();
  2203. }
  2204. void XMLDocument::PrintError() const
  2205. {
  2206. printf("%s\n", ErrorStr());
  2207. }
  2208. const char* XMLDocument::ErrorName() const
  2209. {
  2210. return ErrorIDToName(_errorID);
  2211. }
  2212. void XMLDocument::Parse()
  2213. {
  2214. TIXMLASSERT(NoChildren()); // Clear() must have been called previously
  2215. TIXMLASSERT(_charBuffer);
  2216. _parseCurLineNum = 1;
  2217. _parseLineNum = 1;
  2218. char* p = _charBuffer;
  2219. p = XMLUtil::SkipWhiteSpace(p, &_parseCurLineNum);
  2220. p = const_cast<char*>(XMLUtil::ReadBOM(p, &_writeBOM));
  2221. if (!*p)
  2222. {
  2223. SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0);
  2224. return;
  2225. }
  2226. ParseDeep(p, 0, &_parseCurLineNum);
  2227. }
  2228. void XMLDocument::PushDepth()
  2229. {
  2230. _parsingDepth++;
  2231. if (_parsingDepth == TINYXML2_MAX_ELEMENT_DEPTH)
  2232. {
  2233. SetError(XML_ELEMENT_DEPTH_EXCEEDED, _parseCurLineNum, "Element nesting is too deep.");
  2234. }
  2235. }
  2236. void XMLDocument::PopDepth()
  2237. {
  2238. TIXMLASSERT(_parsingDepth > 0);
  2239. --_parsingDepth;
  2240. }
  2241. XMLPrinter::XMLPrinter(FILE* file, bool compact, int depth) : _elementJustOpened(false),
  2242. _stack(),
  2243. _firstElement(true),
  2244. _fp(file),
  2245. _depth(depth),
  2246. _textDepth(-1),
  2247. _processEntities(true),
  2248. _compactMode(compact),
  2249. _buffer()
  2250. {
  2251. for (int i = 0; i < ENTITY_RANGE; ++i)
  2252. {
  2253. _entityFlag[i] = false;
  2254. _restrictedEntityFlag[i] = false;
  2255. }
  2256. for (int i = 0; i < NUM_ENTITIES; ++i)
  2257. {
  2258. const char entityValue = entities[i].value;
  2259. const unsigned char flagIndex = (unsigned char)entityValue;
  2260. TIXMLASSERT(flagIndex < ENTITY_RANGE);
  2261. _entityFlag[flagIndex] = true;
  2262. }
  2263. _restrictedEntityFlag[(unsigned char)'&'] = true;
  2264. _restrictedEntityFlag[(unsigned char)'<'] = true;
  2265. _restrictedEntityFlag[(unsigned char)'>'] = true; // not required, but consistency is nice
  2266. _buffer.Push(0);
  2267. }
  2268. void XMLPrinter::Print(const char* format, ...)
  2269. {
  2270. va_list va;
  2271. va_start(va, format);
  2272. if (_fp)
  2273. {
  2274. vfprintf(_fp, format, va);
  2275. }
  2276. else
  2277. {
  2278. const int len = TIXML_VSCPRINTF(format, va);
  2279. // Close out and re-start the va-args
  2280. va_end(va);
  2281. TIXMLASSERT(len >= 0);
  2282. va_start(va, format);
  2283. TIXMLASSERT(_buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0);
  2284. char* p = _buffer.PushArr(len) - 1; // back up over the null terminator.
  2285. TIXML_VSNPRINTF(p, len + 1, format, va);
  2286. }
  2287. va_end(va);
  2288. }
  2289. void XMLPrinter::Write(const char* data, size_t size)
  2290. {
  2291. if (_fp)
  2292. {
  2293. fwrite(data, sizeof(char), size, _fp);
  2294. }
  2295. else
  2296. {
  2297. char* p = _buffer.PushArr(static_cast<int>(size)) - 1; // back up over the null terminator.
  2298. memcpy(p, data, size);
  2299. p[size] = 0;
  2300. }
  2301. }
  2302. void XMLPrinter::Putc(char ch)
  2303. {
  2304. if (_fp)
  2305. {
  2306. fputc(ch, _fp);
  2307. }
  2308. else
  2309. {
  2310. char* p = _buffer.PushArr(sizeof(char)) - 1; // back up over the null terminator.
  2311. p[0] = ch;
  2312. p[1] = 0;
  2313. }
  2314. }
  2315. void XMLPrinter::PrintSpace(int depth)
  2316. {
  2317. for (int i = 0; i < depth; ++i)
  2318. {
  2319. Write(" ");
  2320. }
  2321. }
  2322. void XMLPrinter::PrintString(const char* p, bool restricted)
  2323. {
  2324. // Look for runs of bytes between entities to print.
  2325. const char* q = p;
  2326. if (_processEntities)
  2327. {
  2328. const bool* flag = restricted ? _restrictedEntityFlag : _entityFlag;
  2329. while (*q)
  2330. {
  2331. TIXMLASSERT(p <= q);
  2332. // Remember, char is sometimes signed. (How many times has that bitten me?)
  2333. if (*q > 0 && *q < ENTITY_RANGE)
  2334. {
  2335. // Check for entities. If one is found, flush
  2336. // the stream up until the entity, write the
  2337. // entity, and keep looking.
  2338. if (flag[(unsigned char)(*q)])
  2339. {
  2340. while (p < q)
  2341. {
  2342. const size_t delta = q - p;
  2343. const int toPrint = (INT_MAX < delta) ? INT_MAX : (int)delta;
  2344. Write(p, toPrint);
  2345. p += toPrint;
  2346. }
  2347. bool entityPatternPrinted = false;
  2348. for (int i = 0; i < NUM_ENTITIES; ++i)
  2349. {
  2350. if (entities[i].value == *q)
  2351. {
  2352. Putc('&');
  2353. Write(entities[i].pattern, entities[i].length);
  2354. Putc(';');
  2355. entityPatternPrinted = true;
  2356. break;
  2357. }
  2358. }
  2359. if (!entityPatternPrinted)
  2360. {
  2361. // TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable in release
  2362. TIXMLASSERT(false);
  2363. }
  2364. ++p;
  2365. }
  2366. }
  2367. ++q;
  2368. TIXMLASSERT(p <= q);
  2369. }
  2370. }
  2371. // Flush the remaining string. This will be the entire
  2372. // string if an entity wasn't found.
  2373. TIXMLASSERT(p <= q);
  2374. if (!_processEntities || (p < q))
  2375. {
  2376. const size_t delta = q - p;
  2377. const int toPrint = (INT_MAX < delta) ? INT_MAX : (int)delta;
  2378. Write(p, toPrint);
  2379. }
  2380. }
  2381. void XMLPrinter::PushHeader(bool writeBOM, bool writeDec)
  2382. {
  2383. if (writeBOM)
  2384. {
  2385. static const unsigned char bom[] = {TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0};
  2386. Write(reinterpret_cast<const char*>(bom));
  2387. }
  2388. if (writeDec)
  2389. {
  2390. PushDeclaration("xml version=\"1.0\"");
  2391. }
  2392. }
  2393. void XMLPrinter::OpenElement(const char* name, bool compactMode)
  2394. {
  2395. SealElementIfJustOpened();
  2396. _stack.Push(name);
  2397. if (_textDepth < 0 && !_firstElement && !compactMode)
  2398. {
  2399. Putc('\n');
  2400. }
  2401. if (!compactMode)
  2402. {
  2403. PrintSpace(_depth);
  2404. }
  2405. Write("<");
  2406. Write(name);
  2407. _elementJustOpened = true;
  2408. _firstElement = false;
  2409. ++_depth;
  2410. }
  2411. void XMLPrinter::PushAttribute(const char* name, const char* value)
  2412. {
  2413. TIXMLASSERT(_elementJustOpened);
  2414. Putc(' ');
  2415. Write(name);
  2416. Write("=\"");
  2417. PrintString(value, false);
  2418. Putc('\"');
  2419. }
  2420. void XMLPrinter::PushAttribute(const char* name, int v)
  2421. {
  2422. char buf[BUF_SIZE];
  2423. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2424. PushAttribute(name, buf);
  2425. }
  2426. void XMLPrinter::PushAttribute(const char* name, unsigned v)
  2427. {
  2428. char buf[BUF_SIZE];
  2429. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2430. PushAttribute(name, buf);
  2431. }
  2432. void XMLPrinter::PushAttribute(const char* name, xml_Int64a_t v)
  2433. {
  2434. char buf[BUF_SIZE];
  2435. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2436. PushAttribute(name, buf);
  2437. }
  2438. void XMLPrinter::PushAttribute(const char* name, bool v)
  2439. {
  2440. char buf[BUF_SIZE];
  2441. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2442. PushAttribute(name, buf);
  2443. }
  2444. void XMLPrinter::PushAttribute(const char* name, double v)
  2445. {
  2446. char buf[BUF_SIZE];
  2447. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2448. PushAttribute(name, buf);
  2449. }
  2450. void XMLPrinter::CloseElement(bool compactMode)
  2451. {
  2452. --_depth;
  2453. const char* name = _stack.Pop();
  2454. if (_elementJustOpened)
  2455. {
  2456. Write("/>");
  2457. }
  2458. else
  2459. {
  2460. if (_textDepth < 0 && !compactMode)
  2461. {
  2462. Putc('\n');
  2463. PrintSpace(_depth);
  2464. }
  2465. Write("</");
  2466. Write(name);
  2467. Write(">");
  2468. }
  2469. if (_textDepth == _depth)
  2470. {
  2471. _textDepth = -1;
  2472. }
  2473. if (_depth == 0 && !compactMode)
  2474. {
  2475. Putc('\n');
  2476. }
  2477. _elementJustOpened = false;
  2478. }
  2479. void XMLPrinter::SealElementIfJustOpened()
  2480. {
  2481. if (!_elementJustOpened)
  2482. {
  2483. return;
  2484. }
  2485. _elementJustOpened = false;
  2486. Putc('>');
  2487. }
  2488. void XMLPrinter::PushText(const char* text, bool cdata)
  2489. {
  2490. _textDepth = _depth - 1;
  2491. SealElementIfJustOpened();
  2492. if (cdata)
  2493. {
  2494. Write("<![CDATA[");
  2495. Write(text);
  2496. Write("]]>");
  2497. }
  2498. else
  2499. {
  2500. PrintString(text, true);
  2501. }
  2502. }
  2503. void XMLPrinter::PushText(xml_Int64a_t value)
  2504. {
  2505. char buf[BUF_SIZE];
  2506. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2507. PushText(buf, false);
  2508. }
  2509. void XMLPrinter::PushText(int value)
  2510. {
  2511. char buf[BUF_SIZE];
  2512. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2513. PushText(buf, false);
  2514. }
  2515. void XMLPrinter::PushText(unsigned value)
  2516. {
  2517. char buf[BUF_SIZE];
  2518. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2519. PushText(buf, false);
  2520. }
  2521. void XMLPrinter::PushText(bool value)
  2522. {
  2523. char buf[BUF_SIZE];
  2524. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2525. PushText(buf, false);
  2526. }
  2527. void XMLPrinter::PushText(float value)
  2528. {
  2529. char buf[BUF_SIZE];
  2530. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2531. PushText(buf, false);
  2532. }
  2533. void XMLPrinter::PushText(double value)
  2534. {
  2535. char buf[BUF_SIZE];
  2536. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2537. PushText(buf, false);
  2538. }
  2539. void XMLPrinter::PushComment(const char* comment)
  2540. {
  2541. SealElementIfJustOpened();
  2542. if (_textDepth < 0 && !_firstElement && !_compactMode)
  2543. {
  2544. Putc('\n');
  2545. PrintSpace(_depth);
  2546. }
  2547. _firstElement = false;
  2548. Write("<!--");
  2549. Write(comment);
  2550. Write("-->");
  2551. }
  2552. void XMLPrinter::PushDeclaration(const char* value)
  2553. {
  2554. SealElementIfJustOpened();
  2555. if (_textDepth < 0 && !_firstElement && !_compactMode)
  2556. {
  2557. Putc('\n');
  2558. PrintSpace(_depth);
  2559. }
  2560. _firstElement = false;
  2561. Write("<?");
  2562. Write(value);
  2563. Write("?>");
  2564. }
  2565. void XMLPrinter::PushUnknown(const char* value)
  2566. {
  2567. SealElementIfJustOpened();
  2568. if (_textDepth < 0 && !_firstElement && !_compactMode)
  2569. {
  2570. Putc('\n');
  2571. PrintSpace(_depth);
  2572. }
  2573. _firstElement = false;
  2574. Write("<!");
  2575. Write(value);
  2576. Putc('>');
  2577. }
  2578. bool XMLPrinter::VisitEnter(const XMLDocument& doc)
  2579. {
  2580. _processEntities = doc.ProcessEntities();
  2581. if (doc.HasBOM())
  2582. {
  2583. PushHeader(true, false);
  2584. }
  2585. return true;
  2586. }
  2587. bool XMLPrinter::VisitEnter(const XMLElement& element, const XMLAttribute* attribute)
  2588. {
  2589. const XMLElement* parentElem = 0;
  2590. if (element.Parent())
  2591. {
  2592. parentElem = element.Parent()->ToElement();
  2593. }
  2594. const bool compactMode = parentElem ? CompactMode(*parentElem) : _compactMode;
  2595. OpenElement(element.Name(), compactMode);
  2596. while (attribute)
  2597. {
  2598. PushAttribute(attribute->Name(), attribute->Value());
  2599. attribute = attribute->Next();
  2600. }
  2601. return true;
  2602. }
  2603. bool XMLPrinter::VisitExit(const XMLElement& element)
  2604. {
  2605. CloseElement(CompactMode(element));
  2606. return true;
  2607. }
  2608. bool XMLPrinter::Visit(const XMLText& text)
  2609. {
  2610. PushText(text.Value(), text.CData());
  2611. return true;
  2612. }
  2613. bool XMLPrinter::Visit(const XMLComment& comment)
  2614. {
  2615. PushComment(comment.Value());
  2616. return true;
  2617. }
  2618. bool XMLPrinter::Visit(const XMLDeclaration& declaration)
  2619. {
  2620. PushDeclaration(declaration.Value());
  2621. return true;
  2622. }
  2623. bool XMLPrinter::Visit(const XMLUnknown& unknown)
  2624. {
  2625. PushUnknown(unknown.Value());
  2626. return true;
  2627. }
  2628. } // namespace tinyxml2