You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tinyxml2.h 63KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063
  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. #ifndef TINYXML2_INCLUDED
  19. #define TINYXML2_INCLUDED
  20. #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
  21. # include <ctype.h>
  22. # include <limits.h>
  23. # include <stdio.h>
  24. # include <stdlib.h>
  25. # include <string.h>
  26. # if defined(__PS3__)
  27. # include <stddef.h>
  28. # endif
  29. #else
  30. # include <cctype>
  31. # include <climits>
  32. # include <cstdio>
  33. # include <cstdlib>
  34. # include <cstring>
  35. #endif
  36. #include <stdint.h>
  37. /*
  38. TODO: intern strings instead of allocation.
  39. */
  40. /*
  41. gcc:
  42. g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe
  43. Formatting, Artistic Style:
  44. AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h
  45. */
  46. #if defined( _DEBUG ) || defined (__DEBUG__)
  47. # ifndef TINYXML2_DEBUG
  48. # define TINYXML2_DEBUG
  49. # endif
  50. #endif
  51. #ifdef _MSC_VER
  52. # pragma warning(push)
  53. # pragma warning(disable: 4251)
  54. #endif
  55. #ifdef _WIN32
  56. # ifdef TINYXML2_EXPORT
  57. # define TINYXML2_LIB __declspec(dllexport)
  58. # elif defined(TINYXML2_IMPORT)
  59. # define TINYXML2_LIB __declspec(dllimport)
  60. # else
  61. # define TINYXML2_LIB
  62. # endif
  63. #elif __GNUC__ >= 4
  64. # define TINYXML2_LIB __attribute__((visibility("default")))
  65. #else
  66. # define TINYXML2_LIB
  67. #endif
  68. #if defined(TINYXML2_DEBUG)
  69. # if defined(_MSC_VER)
  70. # // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like
  71. # define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); }
  72. # elif defined (ANDROID_NDK)
  73. # include <android/log.h>
  74. # define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); }
  75. # else
  76. # include <assert.h>
  77. # define TIXMLASSERT assert
  78. # endif
  79. #else
  80. # define TIXMLASSERT( x ) {}
  81. #endif
  82. /* Versioning, past 1.0.14:
  83. http://semver.org/
  84. */
  85. static const int TIXML2_MAJOR_VERSION = 7;
  86. static const int TIXML2_MINOR_VERSION = 0;
  87. static const int TIXML2_PATCH_VERSION = 1;
  88. #define TINYXML2_MAJOR_VERSION 7
  89. #define TINYXML2_MINOR_VERSION 0
  90. #define TINYXML2_PATCH_VERSION 1
  91. // A fixed element depth limit is problematic. There needs to be a
  92. // limit to avoid a stack overflow. However, that limit varies per
  93. // system, and the capacity of the stack. On the other hand, it's a trivial
  94. // attack that can result from ill, malicious, or even correctly formed XML,
  95. // so there needs to be a limit in place.
  96. static const int TINYXML2_MAX_ELEMENT_DEPTH = 100;
  97. namespace tinyxml2
  98. {
  99. class XMLDocument;
  100. class XMLElement;
  101. class XMLAttribute;
  102. class XMLComment;
  103. class XMLText;
  104. class XMLDeclaration;
  105. class XMLUnknown;
  106. class XMLPrinter;
  107. /*
  108. A class that wraps strings. Normally stores the start and end
  109. pointers into the XML file itself, and will apply normalization
  110. and entity translation if actually read. Can also store (and memory
  111. manage) a traditional char[]
  112. Isn't clear why TINYXML2_LIB is needed; but seems to fix #719
  113. */
  114. class TINYXML2_LIB StrPair
  115. {
  116. public:
  117. enum
  118. {
  119. NEEDS_ENTITY_PROCESSING = 0x01,
  120. NEEDS_NEWLINE_NORMALIZATION = 0x02,
  121. NEEDS_WHITESPACE_COLLAPSING = 0x04,
  122. TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
  123. TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
  124. ATTRIBUTE_NAME = 0,
  125. ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
  126. ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
  127. COMMENT = NEEDS_NEWLINE_NORMALIZATION
  128. };
  129. StrPair() {}
  130. ~StrPair();
  131. void Set(char* start, char* end, const int flags)
  132. {
  133. TIXMLASSERT(start);
  134. TIXMLASSERT(end);
  135. Reset();
  136. _start = start;
  137. _end = end;
  138. _flags = flags | NEEDS_FLUSH;
  139. }
  140. const char* GetStr();
  141. bool Empty() const { return _start == _end; }
  142. void SetInternedStr(const char* str)
  143. {
  144. Reset();
  145. _start = const_cast<char*>(str);
  146. }
  147. void SetStr(const char* str, int flags = 0);
  148. char* ParseText(char* in, const char* endTag, int strFlags, int* curLineNumPtr);
  149. char* ParseName(char* in);
  150. void TransferTo(StrPair* other);
  151. void Reset();
  152. private:
  153. void CollapseWhitespace();
  154. enum
  155. {
  156. NEEDS_FLUSH = 0x100,
  157. NEEDS_DELETE = 0x200
  158. };
  159. int _flags = 0;
  160. char* _start = nullptr;
  161. char* _end = nullptr;
  162. StrPair(const StrPair& other) = delete; // not supported
  163. void operator=(const StrPair& other) = delete; // not supported, use TransferTo()
  164. };
  165. /*
  166. A dynamic array of Plain Old Data. Doesn't support constructors, etc.
  167. Has a small initial memory pool, so that low or no usage will not
  168. cause a call to new/delete
  169. */
  170. template <class T, int INITIAL_SIZE>
  171. class DynArray
  172. {
  173. public:
  174. DynArray() : _mem(_pool) { }
  175. ~DynArray() { if (_mem != _pool) { delete[] _mem; } }
  176. void Clear() { _size = 0; }
  177. void Push(T t)
  178. {
  179. TIXMLASSERT(_size < INT_MAX);
  180. EnsureCapacity(_size + 1);
  181. _mem[_size] = t;
  182. ++_size;
  183. }
  184. T* PushArr(const int count)
  185. {
  186. TIXMLASSERT(count >= 0);
  187. TIXMLASSERT(_size <= INT_MAX - count);
  188. EnsureCapacity(_size + count);
  189. T* ret = &_mem[_size];
  190. _size += count;
  191. return ret;
  192. }
  193. T Pop()
  194. {
  195. TIXMLASSERT(_size > 0);
  196. --_size;
  197. return _mem[_size];
  198. }
  199. void PopArr(const int count)
  200. {
  201. TIXMLASSERT(_size >= count);
  202. _size -= count;
  203. }
  204. bool Empty() const { return _size == 0; }
  205. T& operator[](int i)
  206. {
  207. TIXMLASSERT(i >= 0 && i < _size);
  208. return _mem[i];
  209. }
  210. const T& operator[](int i) const
  211. {
  212. TIXMLASSERT(i >= 0 && i < _size);
  213. return _mem[i];
  214. }
  215. const T& PeekTop() const
  216. {
  217. TIXMLASSERT(_size > 0);
  218. return _mem[_size - 1];
  219. }
  220. int Size() const
  221. {
  222. TIXMLASSERT(_size >= 0);
  223. return _size;
  224. }
  225. int Capacity() const
  226. {
  227. TIXMLASSERT(_allocated >= INITIAL_SIZE);
  228. return _allocated;
  229. }
  230. void SwapRemove(int i)
  231. {
  232. TIXMLASSERT(i >= 0 && i < _size);
  233. TIXMLASSERT(_size > 0);
  234. _mem[i] = _mem[_size - 1];
  235. --_size;
  236. }
  237. const T* Mem() const
  238. {
  239. TIXMLASSERT(_mem);
  240. return _mem;
  241. }
  242. T* Mem()
  243. {
  244. TIXMLASSERT(_mem);
  245. return _mem;
  246. }
  247. private:
  248. DynArray(const DynArray&) = delete; // not supported
  249. void operator=(const DynArray&) = delete; // not supported
  250. void EnsureCapacity(const int cap)
  251. {
  252. TIXMLASSERT(cap > 0);
  253. if (cap > _allocated)
  254. {
  255. TIXMLASSERT(cap <= INT_MAX / 2);
  256. const int newAllocated = cap * 2;
  257. T* newMem = new T[newAllocated];
  258. TIXMLASSERT(newAllocated >= _size);
  259. memcpy(newMem, _mem, sizeof(T) * _size); // warning: not using constructors, only works for PODs
  260. if (_mem != _pool) { delete[] _mem; }
  261. _mem = newMem;
  262. _allocated = newAllocated;
  263. }
  264. }
  265. T* _mem;
  266. T _pool[INITIAL_SIZE];
  267. int _allocated = INITIAL_SIZE; // objects allocated
  268. int _size = 0; // number objects in use
  269. };
  270. /*
  271. Parent virtual class of a pool for fast allocation
  272. and deallocation of objects.
  273. */
  274. class MemPool
  275. {
  276. public:
  277. MemPool() {}
  278. virtual ~MemPool() {}
  279. virtual int ItemSize() const = 0;
  280. virtual void* Alloc() = 0;
  281. virtual void Free(void*) = 0;
  282. virtual void SetTracked() = 0;
  283. };
  284. /*
  285. Template child class to create pools of the correct type.
  286. */
  287. template <int ITEM_SIZE>
  288. class MemPoolT : public MemPool
  289. {
  290. public:
  291. MemPoolT() : _blockPtrs(), _root(nullptr) {}
  292. ~MemPoolT() override { Clear(); }
  293. void Clear()
  294. {
  295. // Delete the blocks.
  296. while (!_blockPtrs.Empty())
  297. {
  298. Block* lastBlock = _blockPtrs.Pop();
  299. delete lastBlock;
  300. }
  301. _root = 0;
  302. _currentAllocs = 0;
  303. _nAllocs = 0;
  304. _maxAllocs = 0;
  305. _nUntracked = 0;
  306. }
  307. int ItemSize() const override { return ITEM_SIZE; }
  308. int CurrentAllocs() const { return _currentAllocs; }
  309. void* Alloc() override
  310. {
  311. if (!_root)
  312. {
  313. // Need a new block.
  314. Block* block = new Block();
  315. _blockPtrs.Push(block);
  316. Item* blockItems = block->items;
  317. for (int i = 0; i < ITEMS_PER_BLOCK - 1; ++i) { blockItems[i].next = &(blockItems[i + 1]); }
  318. blockItems[ITEMS_PER_BLOCK - 1].next = 0;
  319. _root = blockItems;
  320. }
  321. Item* const result = _root;
  322. TIXMLASSERT(result != nullptr);
  323. _root = _root->next;
  324. ++_currentAllocs;
  325. if (_currentAllocs > _maxAllocs) { _maxAllocs = _currentAllocs; }
  326. ++_nAllocs;
  327. ++_nUntracked;
  328. return result;
  329. }
  330. void Free(void* mem) override
  331. {
  332. if (!mem) { return; }
  333. --_currentAllocs;
  334. Item* item = static_cast<Item*>(mem);
  335. #ifdef TINYXML2_DEBUG
  336. memset(item, 0xfe, sizeof(*item));
  337. #endif
  338. item->next = _root;
  339. _root = item;
  340. }
  341. void Trace(const char* name)
  342. {
  343. printf("Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n",
  344. name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs,
  345. ITEM_SIZE, _nAllocs, _blockPtrs.Size());
  346. }
  347. void SetTracked() override { --_nUntracked; }
  348. int Untracked() const { return _nUntracked; }
  349. // This number is perf sensitive. 4k seems like a good tradeoff on my machine.
  350. // The test file is large, 170k.
  351. // Release: VS2010 gcc(no opt)
  352. // 1k: 4000
  353. // 2k: 4000
  354. // 4k: 3900 21000
  355. // 16k: 5200
  356. // 32k: 4300
  357. // 64k: 4000 21000
  358. // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK
  359. // in private part if ITEMS_PER_BLOCK is private
  360. enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE };
  361. private:
  362. MemPoolT(const MemPoolT&) = delete; // not supported
  363. void operator=(const MemPoolT&) = delete; // not supported
  364. union Item
  365. {
  366. Item* next;
  367. char itemData[ITEM_SIZE];
  368. };
  369. struct Block
  370. {
  371. Item items[ITEMS_PER_BLOCK];
  372. };
  373. DynArray<Block*, 10> _blockPtrs;
  374. Item* _root = nullptr;
  375. int _currentAllocs = 0;
  376. int _nAllocs = 0;
  377. int _maxAllocs = 0;
  378. int _nUntracked = 0;
  379. };
  380. /**
  381. Implements the interface to the "Visitor pattern" (see the Accept() method.)
  382. If you call the Accept() method, it requires being passed a XMLVisitor
  383. class to handle callbacks. For nodes that contain other nodes (Document, Element)
  384. you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs
  385. are simply called with Visit().
  386. If you return 'true' from a Visit method, recursive parsing will continue. If you return
  387. false, <b>no children of this node or its siblings</b> will be visited.
  388. All flavors of Visit methods have a default implementation that returns 'true' (continue
  389. visiting). You need to only override methods that are interesting to you.
  390. Generally Accept() is called on the XMLDocument, although all nodes support visiting.
  391. You should never change the document from a callback.
  392. @sa XMLNode::Accept()
  393. */
  394. class TINYXML2_LIB XMLVisitor
  395. {
  396. public:
  397. virtual ~XMLVisitor() {}
  398. /// Visit a document.
  399. virtual bool VisitEnter(const XMLDocument& /*doc*/) { return true; }
  400. /// Visit a document.
  401. virtual bool VisitExit(const XMLDocument& /*doc*/) { return true; }
  402. /// Visit an element.
  403. virtual bool VisitEnter(const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/) { return true; }
  404. /// Visit an element.
  405. virtual bool VisitExit(const XMLElement& /*element*/) { return true; }
  406. /// Visit a declaration.
  407. virtual bool Visit(const XMLDeclaration& /*declaration*/) { return true; }
  408. /// Visit a text node.
  409. virtual bool Visit(const XMLText& /*text*/) { return true; }
  410. /// Visit a comment node.
  411. virtual bool Visit(const XMLComment& /*comment*/) { return true; }
  412. /// Visit an unknown node.
  413. virtual bool Visit(const XMLUnknown& /*unknown*/) { return true; }
  414. };
  415. // WARNING: must match XMLDocument::_errorNames[]
  416. enum XMLError
  417. {
  418. XML_SUCCESS = 0,
  419. XML_NO_ATTRIBUTE,
  420. XML_WRONG_ATTRIBUTE_TYPE,
  421. XML_ERROR_FILE_NOT_FOUND,
  422. XML_ERROR_FILE_COULD_NOT_BE_OPENED,
  423. XML_ERROR_FILE_READ_ERROR,
  424. XML_ERROR_PARSING_ELEMENT,
  425. XML_ERROR_PARSING_ATTRIBUTE,
  426. XML_ERROR_PARSING_TEXT,
  427. XML_ERROR_PARSING_CDATA,
  428. XML_ERROR_PARSING_COMMENT,
  429. XML_ERROR_PARSING_DECLARATION,
  430. XML_ERROR_PARSING_UNKNOWN,
  431. XML_ERROR_EMPTY_DOCUMENT,
  432. XML_ERROR_MISMATCHED_ELEMENT,
  433. XML_ERROR_PARSING,
  434. XML_CAN_NOT_CONVERT_TEXT,
  435. XML_NO_TEXT_NODE,
  436. XML_ELEMENT_DEPTH_EXCEEDED,
  437. XML_ERROR_COUNT
  438. };
  439. /*
  440. Utility functionality.
  441. */
  442. class TINYXML2_LIB XMLUtil
  443. {
  444. public:
  445. static const char* SkipWhiteSpace(const char* p, int* curLineNumPtr)
  446. {
  447. TIXMLASSERT(p);
  448. while (IsWhiteSpace(*p))
  449. {
  450. if (curLineNumPtr && *p == '\n') { ++(*curLineNumPtr); }
  451. ++p;
  452. }
  453. TIXMLASSERT(p);
  454. return p;
  455. }
  456. static char* SkipWhiteSpace(char* p, int* curLineNumPtr) { return const_cast<char*>(SkipWhiteSpace(const_cast<const char*>(p), curLineNumPtr)); }
  457. // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't
  458. // correct, but simple, and usually works.
  459. static bool IsWhiteSpace(const char p) { return !IsUTF8Continuation(p) && isspace(static_cast<unsigned char>(p)); }
  460. static bool IsNameStartChar(const unsigned char ch)
  461. {
  462. if (ch >= 128) { return true; } // This is a heuristic guess in attempt to not implement Unicode-aware isalpha()
  463. if (isalpha(ch)) { return true; }
  464. return ch == ':' || ch == '_';
  465. }
  466. static bool IsNameChar(const unsigned char ch) { return IsNameStartChar(ch) || isdigit(ch) || ch == '.' || ch == '-'; }
  467. static bool StringEqual(const char* p, const char* q, const int nChar = INT_MAX)
  468. {
  469. if (p == q) { return true; }
  470. TIXMLASSERT(p);
  471. TIXMLASSERT(q);
  472. TIXMLASSERT(nChar >= 0);
  473. return strncmp(p, q, nChar) == 0;
  474. }
  475. static bool IsUTF8Continuation(const char p) { return (p & 0x80) != 0; }
  476. static const char* ReadBOM(const char* p, bool* bom);
  477. // p is the starting location,
  478. // the UTF-8 value of the entity will be placed in value, and length filled in.
  479. static const char* GetCharacterRef(const char* p, char* value, int* length);
  480. static void ConvertUTF32ToUTF8(unsigned long input, char* output, int* length);
  481. // converts primitive types to strings
  482. static void ToStr(int value, char* buffer, int size);
  483. static void ToStr(unsigned value, char* buffer, int size);
  484. static void ToStr(bool value, char* buffer, int size);
  485. static void ToStr(float value, char* buffer, int size);
  486. static void ToStr(double value, char* buffer, int size);
  487. static void ToStr(int64_t value, char* buffer, int size);
  488. // converts strings to primitive types
  489. static bool ToInt(const char* str, int* value);
  490. static bool ToUnsigned(const char* str, unsigned* value);
  491. static bool ToBool(const char* str, bool* value);
  492. static bool ToFloat(const char* str, float* value);
  493. static bool ToDouble(const char* str, double* value);
  494. static bool ToInt64(const char* str, int64_t* value);
  495. // Changes what is serialized for a boolean value.
  496. // Default to "true" and "false". Shouldn't be changed
  497. // unless you have a special testing or compatibility need.
  498. // Be careful: static, global, & not thread safe.
  499. // Be sure to set static const memory as parameters.
  500. static void SetBoolSerialization(const char* writeTrue, const char* writeFalse);
  501. private:
  502. static const char* writeBoolTrue;
  503. static const char* writeBoolFalse;
  504. };
  505. /** XMLNode is a base class for every object that is in the
  506. XML Document Object Model (DOM), except XMLAttributes.
  507. Nodes have siblings, a parent, and children which can
  508. be navigated. A node is always in a XMLDocument.
  509. The type of a XMLNode can be queried, and it can
  510. be cast to its more defined type.
  511. A XMLDocument allocates memory for all its Nodes.
  512. When the XMLDocument gets deleted, all its Nodes
  513. will also be deleted.
  514. @verbatim
  515. A Document can contain: Element (container or leaf)
  516. Comment (leaf)
  517. Unknown (leaf)
  518. Declaration( leaf )
  519. An Element can contain: Element (container or leaf)
  520. Text (leaf)
  521. Attributes (not on tree)
  522. Comment (leaf)
  523. Unknown (leaf)
  524. @endverbatim
  525. */
  526. class TINYXML2_LIB XMLNode
  527. {
  528. friend class XMLDocument;
  529. friend class XMLElement;
  530. public:
  531. /// Get the XMLDocument that owns this XMLNode.
  532. const XMLDocument* GetDocument() const
  533. {
  534. TIXMLASSERT(_document);
  535. return _document;
  536. }
  537. /// Get the XMLDocument that owns this XMLNode.
  538. XMLDocument* GetDocument()
  539. {
  540. TIXMLASSERT(_document);
  541. return _document;
  542. }
  543. /// Safely cast to an Element, or null.
  544. virtual XMLElement* ToElement() { return nullptr; }
  545. /// Safely cast to Text, or null.
  546. virtual XMLText* ToText() { return nullptr; }
  547. /// Safely cast to a Comment, or null.
  548. virtual XMLComment* ToComment() { return nullptr; }
  549. /// Safely cast to a Document, or null.
  550. virtual XMLDocument* ToDocument() { return nullptr; }
  551. /// Safely cast to a Declaration, or null.
  552. virtual XMLDeclaration* ToDeclaration() { return nullptr; }
  553. /// Safely cast to an Unknown, or null.
  554. virtual XMLUnknown* ToUnknown() { return nullptr; }
  555. virtual const XMLElement* ToElement() const { return nullptr; }
  556. virtual const XMLText* ToText() const { return nullptr; }
  557. virtual const XMLComment* ToComment() const { return nullptr; }
  558. virtual const XMLDocument* ToDocument() const { return nullptr; }
  559. virtual const XMLDeclaration* ToDeclaration() const { return nullptr; }
  560. virtual const XMLUnknown* ToUnknown() const { return nullptr; }
  561. /** The meaning of 'value' changes for the specific type.
  562. @verbatim
  563. Document: empty (NULL is returned, not an empty string)
  564. Element: name of the element
  565. Comment: the comment text
  566. Unknown: the tag contents
  567. Text: the text string
  568. @endverbatim
  569. */
  570. const char* Value() const;
  571. /** Set the Value of an XML node.
  572. @sa Value()
  573. */
  574. void SetValue(const char* val, bool staticMem = false);
  575. /// Gets the line number the node is in, if the document was parsed from a file.
  576. int GetLineNum() const { return _parseLineNum; }
  577. /// Get the parent of this node on the DOM.
  578. const XMLNode* Parent() const { return _parent; }
  579. XMLNode* Parent() { return _parent; }
  580. /// Returns true if this node has no children.
  581. bool NoChildren() const { return !_firstChild; }
  582. /// Get the first child node, or null if none exists.
  583. const XMLNode* FirstChild() const { return _firstChild; }
  584. XMLNode* FirstChild() { return _firstChild; }
  585. /** Get the first child element, or optionally the first child
  586. element with the specified name.
  587. */
  588. const XMLElement* FirstChildElement(const char* name = nullptr) const;
  589. XMLElement* FirstChildElement(const char* name = nullptr) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->FirstChildElement(name)); }
  590. /// Get the last child node, or null if none exists.
  591. const XMLNode* LastChild() const { return _lastChild; }
  592. XMLNode* LastChild() { return _lastChild; }
  593. /** Get the last child element or optionally the last child
  594. element with the specified name.
  595. */
  596. const XMLElement* LastChildElement(const char* name = nullptr) const;
  597. XMLElement* LastChildElement(const char* name = nullptr) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->LastChildElement(name)); }
  598. /// Get the previous (left) sibling node of this node.
  599. const XMLNode* PreviousSibling() const { return _prev; }
  600. XMLNode* PreviousSibling() { return _prev; }
  601. /// Get the previous (left) sibling element of this node, with an optionally supplied name.
  602. const XMLElement* PreviousSiblingElement(const char* name = nullptr) const;
  603. XMLElement* PreviousSiblingElement(const char* name = nullptr)
  604. {
  605. return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->PreviousSiblingElement(name));
  606. }
  607. /// Get the next (right) sibling node of this node.
  608. const XMLNode* NextSibling() const { return _next; }
  609. XMLNode* NextSibling() { return _next; }
  610. /// Get the next (right) sibling element of this node, with an optionally supplied name.
  611. const XMLElement* NextSiblingElement(const char* name = nullptr) const;
  612. XMLElement* NextSiblingElement(const char* name = nullptr)
  613. {
  614. return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->NextSiblingElement(name));
  615. }
  616. /**
  617. Add a child node as the last (right) child.
  618. If the child node is already part of the document,
  619. it is moved from its old location to the new location.
  620. Returns the addThis argument or 0 if the node does not
  621. belong to the same document.
  622. */
  623. XMLNode* InsertEndChild(XMLNode* addThis);
  624. XMLNode* LinkEndChild(XMLNode* addThis) { return InsertEndChild(addThis); }
  625. /**
  626. Add a child node as the first (left) child.
  627. If the child node is already part of the document,
  628. it is moved from its old location to the new location.
  629. Returns the addThis argument or 0 if the node does not
  630. belong to the same document.
  631. */
  632. XMLNode* InsertFirstChild(XMLNode* addThis);
  633. /**
  634. Add a node after the specified child node.
  635. If the child node is already part of the document,
  636. it is moved from its old location to the new location.
  637. Returns the addThis argument or 0 if the afterThis node
  638. is not a child of this node, or if the node does not
  639. belong to the same document.
  640. */
  641. XMLNode* InsertAfterChild(XMLNode* afterThis, XMLNode* addThis);
  642. /**
  643. Delete all the children of this node.
  644. */
  645. void DeleteChildren();
  646. /**
  647. Delete a child of this node.
  648. */
  649. void DeleteChild(XMLNode* node);
  650. /**
  651. Make a copy of this node, but not its children.
  652. You may pass in a Document pointer that will be
  653. the owner of the new Node. If the 'document' is
  654. null, then the node returned will be allocated
  655. from the current Document. (this->GetDocument())
  656. Note: if called on a XMLDocument, this will return null.
  657. */
  658. virtual XMLNode* ShallowClone(XMLDocument* document) const = 0;
  659. /**
  660. Make a copy of this node and all its children.
  661. If the 'target' is null, then the nodes will
  662. be allocated in the current document. If 'target'
  663. is specified, the memory will be allocated is the
  664. specified XMLDocument.
  665. NOTE: This is probably not the correct tool to
  666. copy a document, since XMLDocuments can have multiple
  667. top level XMLNodes. You probably want to use
  668. XMLDocument::DeepCopy()
  669. */
  670. XMLNode* DeepClone(XMLDocument* target) const;
  671. /**
  672. Test if 2 nodes are the same, but don't test children.
  673. The 2 nodes do not need to be in the same Document.
  674. Note: if called on a XMLDocument, this will return false.
  675. */
  676. virtual bool ShallowEqual(const XMLNode* compare) const = 0;
  677. /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the
  678. XML tree will be conditionally visited and the host will be called back
  679. via the XMLVisitor interface.
  680. This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse
  681. the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this
  682. interface versus any other.)
  683. The interface has been based on ideas from:
  684. - http://www.saxproject.org/
  685. - http://c2.com/cgi/wiki?HierarchicalVisitorPattern
  686. Which are both good references for "visiting".
  687. An example of using Accept():
  688. @verbatim
  689. XMLPrinter printer;
  690. tinyxmlDoc.Accept( &printer );
  691. const char* xmlcstr = printer.CStr();
  692. @endverbatim
  693. */
  694. virtual bool Accept(XMLVisitor* visitor) const = 0;
  695. /**
  696. Set user data into the XMLNode. TinyXML-2 in
  697. no way processes or interprets user data.
  698. It is initially 0.
  699. */
  700. void SetUserData(void* userData) { _userData = userData; }
  701. /**
  702. Get user data set into the XMLNode. TinyXML-2 in
  703. no way processes or interprets user data.
  704. It is initially 0.
  705. */
  706. void* GetUserData() const { return _userData; }
  707. protected:
  708. explicit XMLNode(XMLDocument* doc);
  709. virtual ~XMLNode();
  710. virtual char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr);
  711. XMLDocument* _document = nullptr;
  712. XMLNode* _parent = nullptr;
  713. mutable StrPair _value;
  714. int _parseLineNum = 0;
  715. XMLNode* _firstChild = nullptr;
  716. XMLNode* _lastChild = nullptr;
  717. XMLNode* _prev = nullptr;
  718. XMLNode* _next = nullptr;
  719. void* _userData = nullptr;
  720. private:
  721. MemPool* _memPool;
  722. void Unlink(XMLNode* child);
  723. static void DeleteNode(XMLNode* node);
  724. void InsertChildPreamble(XMLNode* insertThis) const;
  725. const XMLElement* ToElementWithName(const char* name) const;
  726. XMLNode(const XMLNode&) = delete; // not supported
  727. XMLNode& operator=(const XMLNode&) = delete; // not supported
  728. };
  729. /** XML text.
  730. Note that a text node can have child element nodes, for example:
  731. @verbatim
  732. <root>This is <b>bold</b></root>
  733. @endverbatim
  734. A text node can have 2 ways to output the next. "normal" output
  735. and CDATA. It will default to the mode it was parsed from the XML file and
  736. you generally want to leave it alone, but you can change the output mode with
  737. SetCData() and query it with CData().
  738. */
  739. class TINYXML2_LIB XMLText : public XMLNode
  740. {
  741. friend class XMLDocument;
  742. public:
  743. bool Accept(XMLVisitor* visitor) const override;
  744. XMLText* ToText() override { return this; }
  745. const XMLText* ToText() const override { return this; }
  746. /// Declare whether this should be CDATA or standard text.
  747. void SetCData(const bool isCData) { _isCData = isCData; }
  748. /// Returns true if this is a CDATA text element.
  749. bool CData() const { return _isCData; }
  750. XMLNode* ShallowClone(XMLDocument* doc) const override;
  751. bool ShallowEqual(const XMLNode* compare) const override;
  752. protected:
  753. explicit XMLText(XMLDocument* doc) : XMLNode(doc), _isCData(false) {}
  754. ~XMLText() override {}
  755. char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) override;
  756. private:
  757. bool _isCData;
  758. XMLText(const XMLText&) = delete; // not supported
  759. XMLText& operator=(const XMLText&) = delete; // not supported
  760. };
  761. /** An XML Comment. */
  762. class TINYXML2_LIB XMLComment : public XMLNode
  763. {
  764. friend class XMLDocument;
  765. public:
  766. XMLComment* ToComment() override { return this; }
  767. const XMLComment* ToComment() const override { return this; }
  768. bool Accept(XMLVisitor* visitor) const override;
  769. XMLNode* ShallowClone(XMLDocument* doc) const override;
  770. bool ShallowEqual(const XMLNode* compare) const override;
  771. protected:
  772. explicit XMLComment(XMLDocument* doc) : XMLNode(doc) { }
  773. ~XMLComment() override { }
  774. char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) override;
  775. private:
  776. XMLComment(const XMLComment&) = delete; // not supported
  777. XMLComment& operator=(const XMLComment&) = delete; // not supported
  778. };
  779. /** In correct XML the declaration is the first entry in the file.
  780. @verbatim
  781. <?xml version="1.0" standalone="yes"?>
  782. @endverbatim
  783. TinyXML-2 will happily read or write files without a declaration,
  784. however.
  785. The text of the declaration isn't interpreted. It is parsed
  786. and written as a string.
  787. */
  788. class TINYXML2_LIB XMLDeclaration : public XMLNode
  789. {
  790. friend class XMLDocument;
  791. public:
  792. XMLDeclaration* ToDeclaration() override { return this; }
  793. const XMLDeclaration* ToDeclaration() const override { return this; }
  794. bool Accept(XMLVisitor* visitor) const override;
  795. XMLNode* ShallowClone(XMLDocument* doc) const override;
  796. bool ShallowEqual(const XMLNode* compare) const override;
  797. protected:
  798. explicit XMLDeclaration(XMLDocument* doc) : XMLNode(doc) { }
  799. ~XMLDeclaration() override { }
  800. char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) override;
  801. private:
  802. XMLDeclaration(const XMLDeclaration&) = delete; // not supported
  803. XMLDeclaration& operator=(const XMLDeclaration&) = delete; // not supported
  804. };
  805. /** Any tag that TinyXML-2 doesn't recognize is saved as an
  806. unknown. It is a tag of text, but should not be modified.
  807. It will be written back to the XML, unchanged, when the file
  808. is saved.
  809. DTD tags get thrown into XMLUnknowns.
  810. */
  811. class TINYXML2_LIB XMLUnknown : public XMLNode
  812. {
  813. friend class XMLDocument;
  814. public:
  815. XMLUnknown* ToUnknown() override { return this; }
  816. const XMLUnknown* ToUnknown() const override { return this; }
  817. bool Accept(XMLVisitor* visitor) const override;
  818. XMLNode* ShallowClone(XMLDocument* doc) const override;
  819. bool ShallowEqual(const XMLNode* compare) const override;
  820. protected:
  821. explicit XMLUnknown(XMLDocument* doc) : XMLNode(doc) { }
  822. ~XMLUnknown() override { }
  823. char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) override;
  824. private:
  825. XMLUnknown(const XMLUnknown&) = delete; // not supported
  826. XMLUnknown& operator=(const XMLUnknown&) = delete; // not supported
  827. };
  828. /** An attribute is a name-value pair. Elements have an arbitrary
  829. number of attributes, each with a unique name.
  830. @note The attributes are not XMLNodes. You may only query the
  831. Next() attribute in a list.
  832. */
  833. class TINYXML2_LIB XMLAttribute
  834. {
  835. friend class XMLElement;
  836. public:
  837. /// The name of the attribute.
  838. const char* Name() const { return _name.GetStr(); }
  839. /// The value of the attribute.
  840. const char* Value() const { return _value.GetStr(); }
  841. /// Gets the line number the attribute is in, if the document was parsed from a file.
  842. int GetLineNum() const { return _parseLineNum; }
  843. /// The next attribute in the list.
  844. const XMLAttribute* Next() const { return _next; }
  845. /** IntValue interprets the attribute as an integer, and returns the value.
  846. If the value isn't an integer, 0 will be returned. There is no error checking;
  847. use QueryIntValue() if you need error checking.
  848. */
  849. int IntValue() const
  850. {
  851. int i = 0;
  852. QueryIntValue(&i);
  853. return i;
  854. }
  855. int64_t Int64Value() const
  856. {
  857. int64_t i = 0;
  858. QueryInt64Value(&i);
  859. return i;
  860. }
  861. /// Query as an unsigned integer. See IntValue()
  862. unsigned UnsignedValue() const
  863. {
  864. unsigned i = 0;
  865. QueryUnsignedValue(&i);
  866. return i;
  867. }
  868. /// Query as a boolean. See IntValue()
  869. bool BoolValue() const
  870. {
  871. bool b = false;
  872. QueryBoolValue(&b);
  873. return b;
  874. }
  875. /// Query as a double. See IntValue()
  876. double DoubleValue() const
  877. {
  878. double d = 0;
  879. QueryDoubleValue(&d);
  880. return d;
  881. }
  882. /// Query as a float. See IntValue()
  883. float FloatValue() const
  884. {
  885. float f = 0;
  886. QueryFloatValue(&f);
  887. return f;
  888. }
  889. /** QueryIntValue interprets the attribute as an integer, and returns the value
  890. in the provided parameter. The function will return XML_SUCCESS on success,
  891. and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful.
  892. */
  893. XMLError QueryIntValue(int* value) const;
  894. /// See QueryIntValue
  895. XMLError QueryUnsignedValue(unsigned int* value) const;
  896. /// See QueryIntValue
  897. XMLError QueryInt64Value(int64_t* value) const;
  898. /// See QueryIntValue
  899. XMLError QueryBoolValue(bool* value) const;
  900. /// See QueryIntValue
  901. XMLError QueryDoubleValue(double* value) const;
  902. /// See QueryIntValue
  903. XMLError QueryFloatValue(float* value) const;
  904. /// Set the attribute to a string value.
  905. void SetAttribute(const char* value) { _value.SetStr(value); }
  906. /// Set the attribute to value.
  907. void SetAttribute(int value);
  908. /// Set the attribute to value.
  909. void SetAttribute(unsigned value);
  910. /// Set the attribute to value.
  911. void SetAttribute(int64_t value);
  912. /// Set the attribute to value.
  913. void SetAttribute(bool value);
  914. /// Set the attribute to value.
  915. void SetAttribute(double value);
  916. /// Set the attribute to value.
  917. void SetAttribute(float value);
  918. private:
  919. enum { BUF_SIZE = 200 };
  920. XMLAttribute() {}
  921. virtual ~XMLAttribute() {}
  922. XMLAttribute(const XMLAttribute&) = delete; // not supported
  923. void operator=(const XMLAttribute&) = delete; // not supported
  924. void SetName(const char* name) { _name.SetStr(name); }
  925. char* ParseDeep(char* p, bool processEntities, int* curLineNumPtr);
  926. mutable StrPair _name;
  927. mutable StrPair _value;
  928. int _parseLineNum = 0;
  929. XMLAttribute* _next = nullptr;
  930. MemPool* _memPool = nullptr;
  931. };
  932. /** The element is a container class. It has a value, the element name,
  933. and can contain other elements, text, comments, and unknowns.
  934. Elements also contain an arbitrary number of attributes.
  935. */
  936. class TINYXML2_LIB XMLElement : public XMLNode
  937. {
  938. friend class XMLDocument;
  939. public:
  940. /// Get the name of an element (which is the Value() of the node.)
  941. const char* Name() const { return Value(); }
  942. /// Set the name of the element.
  943. void SetName(const char* str, const bool staticMem = false) { SetValue(str, staticMem); }
  944. XMLElement* ToElement() override { return this; }
  945. const XMLElement* ToElement() const override { return this; }
  946. bool Accept(XMLVisitor* visitor) const override;
  947. /** Given an attribute name, Attribute() returns the value
  948. for the attribute of that name, or null if none
  949. exists. For example:
  950. @verbatim
  951. const char* value = ele->Attribute( "foo" );
  952. @endverbatim
  953. The 'value' parameter is normally null. However, if specified,
  954. the attribute will only be returned if the 'name' and 'value'
  955. match. This allow you to write code:
  956. @verbatim
  957. if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar();
  958. @endverbatim
  959. rather than:
  960. @verbatim
  961. if ( ele->Attribute( "foo" ) ) { if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); }
  962. @endverbatim
  963. */
  964. const char* Attribute(const char* name, const char* value = nullptr) const;
  965. /** Given an attribute name, IntAttribute() returns the value
  966. of the attribute interpreted as an integer. The default
  967. value will be returned if the attribute isn't present,
  968. or if there is an error. (For a method with error
  969. checking, see QueryIntAttribute()).
  970. */
  971. int IntAttribute(const char* name, int defaultValue = 0) const;
  972. /// See IntAttribute()
  973. unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const;
  974. /// See IntAttribute()
  975. int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const;
  976. /// See IntAttribute()
  977. bool BoolAttribute(const char* name, bool defaultValue = false) const;
  978. /// See IntAttribute()
  979. double DoubleAttribute(const char* name, double defaultValue = 0) const;
  980. /// See IntAttribute()
  981. float FloatAttribute(const char* name, float defaultValue = 0) const;
  982. /** Given an attribute name, QueryIntAttribute() returns
  983. XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion
  984. can't be performed, or XML_NO_ATTRIBUTE if the attribute
  985. doesn't exist. If successful, the result of the conversion
  986. will be written to 'value'. If not successful, nothing will
  987. be written to 'value'. This allows you to provide default
  988. value:
  989. @verbatim
  990. int value = 10;
  991. QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10
  992. @endverbatim
  993. */
  994. XMLError QueryIntAttribute(const char* name, int* value) const
  995. {
  996. const XMLAttribute* a = FindAttribute(name);
  997. if (!a) { return XML_NO_ATTRIBUTE; }
  998. return a->QueryIntValue(value);
  999. }
  1000. /// See QueryIntAttribute()
  1001. XMLError QueryUnsignedAttribute(const char* name, unsigned int* value) const
  1002. {
  1003. const XMLAttribute* a = FindAttribute(name);
  1004. if (!a) { return XML_NO_ATTRIBUTE; }
  1005. return a->QueryUnsignedValue(value);
  1006. }
  1007. /// See QueryIntAttribute()
  1008. XMLError QueryInt64Attribute(const char* name, int64_t* value) const
  1009. {
  1010. const XMLAttribute* a = FindAttribute(name);
  1011. if (!a) { return XML_NO_ATTRIBUTE; }
  1012. return a->QueryInt64Value(value);
  1013. }
  1014. /// See QueryIntAttribute()
  1015. XMLError QueryBoolAttribute(const char* name, bool* value) const
  1016. {
  1017. const XMLAttribute* a = FindAttribute(name);
  1018. if (!a) { return XML_NO_ATTRIBUTE; }
  1019. return a->QueryBoolValue(value);
  1020. }
  1021. /// See QueryIntAttribute()
  1022. XMLError QueryDoubleAttribute(const char* name, double* value) const
  1023. {
  1024. const XMLAttribute* a = FindAttribute(name);
  1025. if (!a) { return XML_NO_ATTRIBUTE; }
  1026. return a->QueryDoubleValue(value);
  1027. }
  1028. /// See QueryIntAttribute()
  1029. XMLError QueryFloatAttribute(const char* name, float* value) const
  1030. {
  1031. const XMLAttribute* a = FindAttribute(name);
  1032. if (!a) { return XML_NO_ATTRIBUTE; }
  1033. return a->QueryFloatValue(value);
  1034. }
  1035. /// See QueryIntAttribute()
  1036. XMLError QueryStringAttribute(const char* name, const char** value) const
  1037. {
  1038. const XMLAttribute* a = FindAttribute(name);
  1039. if (!a) { return XML_NO_ATTRIBUTE; }
  1040. *value = a->Value();
  1041. return XML_SUCCESS;
  1042. }
  1043. /** Given an attribute name, QueryAttribute() returns
  1044. XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion
  1045. can't be performed, or XML_NO_ATTRIBUTE if the attribute
  1046. doesn't exist. It is overloaded for the primitive types,
  1047. and is a generally more convenient replacement of
  1048. QueryIntAttribute() and related functions.
  1049. If successful, the result of the conversion
  1050. will be written to 'value'. If not successful, nothing will
  1051. be written to 'value'. This allows you to provide default
  1052. value:
  1053. @verbatim
  1054. int value = 10;
  1055. QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10
  1056. @endverbatim
  1057. */
  1058. XMLError QueryAttribute(const char* name, int* value) const { return QueryIntAttribute(name, value); }
  1059. XMLError QueryAttribute(const char* name, unsigned int* value) const { return QueryUnsignedAttribute(name, value); }
  1060. XMLError QueryAttribute(const char* name, int64_t* value) const { return QueryInt64Attribute(name, value); }
  1061. XMLError QueryAttribute(const char* name, bool* value) const { return QueryBoolAttribute(name, value); }
  1062. XMLError QueryAttribute(const char* name, double* value) const { return QueryDoubleAttribute(name, value); }
  1063. XMLError QueryAttribute(const char* name, float* value) const { return QueryFloatAttribute(name, value); }
  1064. /// Sets the named attribute to value.
  1065. void SetAttribute(const char* name, const char* value)
  1066. {
  1067. XMLAttribute* a = FindOrCreateAttribute(name);
  1068. a->SetAttribute(value);
  1069. }
  1070. /// Sets the named attribute to value.
  1071. void SetAttribute(const char* name, const int value)
  1072. {
  1073. XMLAttribute* a = FindOrCreateAttribute(name);
  1074. a->SetAttribute(value);
  1075. }
  1076. /// Sets the named attribute to value.
  1077. void SetAttribute(const char* name, const unsigned value)
  1078. {
  1079. XMLAttribute* a = FindOrCreateAttribute(name);
  1080. a->SetAttribute(value);
  1081. }
  1082. /// Sets the named attribute to value.
  1083. void SetAttribute(const char* name, const int64_t value)
  1084. {
  1085. XMLAttribute* a = FindOrCreateAttribute(name);
  1086. a->SetAttribute(value);
  1087. }
  1088. /// Sets the named attribute to value.
  1089. void SetAttribute(const char* name, const bool value)
  1090. {
  1091. XMLAttribute* a = FindOrCreateAttribute(name);
  1092. a->SetAttribute(value);
  1093. }
  1094. /// Sets the named attribute to value.
  1095. void SetAttribute(const char* name, const double value)
  1096. {
  1097. XMLAttribute* a = FindOrCreateAttribute(name);
  1098. a->SetAttribute(value);
  1099. }
  1100. /// Sets the named attribute to value.
  1101. void SetAttribute(const char* name, const float value)
  1102. {
  1103. XMLAttribute* a = FindOrCreateAttribute(name);
  1104. a->SetAttribute(value);
  1105. }
  1106. /**
  1107. Delete an attribute.
  1108. */
  1109. void DeleteAttribute(const char* name);
  1110. /// Return the first attribute in the list.
  1111. const XMLAttribute* FirstAttribute() const { return _rootAttribute; }
  1112. /// Query a specific attribute in the list.
  1113. const XMLAttribute* FindAttribute(const char* name) const;
  1114. /** Convenience function for easy access to the text inside an element. Although easy
  1115. and concise, GetText() is limited compared to getting the XMLText child
  1116. and accessing it directly.
  1117. If the first child of 'this' is a XMLText, the GetText()
  1118. returns the character string of the Text node, else null is returned.
  1119. This is a convenient method for getting the text of simple contained text:
  1120. @verbatim
  1121. <foo>This is text</foo>
  1122. const char* str = fooElement->GetText();
  1123. @endverbatim
  1124. 'str' will be a pointer to "This is text".
  1125. Note that this function can be misleading. If the element foo was created from
  1126. this XML:
  1127. @verbatim
  1128. <foo><b>This is text</b></foo>
  1129. @endverbatim
  1130. then the value of str would be null. The first child node isn't a text node, it is
  1131. another element. From this XML:
  1132. @verbatim
  1133. <foo>This is <b>text</b></foo>
  1134. @endverbatim
  1135. GetText() will return "This is ".
  1136. */
  1137. const char* GetText() const;
  1138. /** Convenience function for easy access to the text inside an element. Although easy
  1139. and concise, SetText() is limited compared to creating an XMLText child
  1140. and mutating it directly.
  1141. If the first child of 'this' is a XMLText, SetText() sets its value to
  1142. the given string, otherwise it will create a first child that is an XMLText.
  1143. This is a convenient method for setting the text of simple contained text:
  1144. @verbatim
  1145. <foo>This is text</foo>
  1146. fooElement->SetText( "Hullaballoo!" );
  1147. <foo>Hullaballoo!</foo>
  1148. @endverbatim
  1149. Note that this function can be misleading. If the element foo was created from
  1150. this XML:
  1151. @verbatim
  1152. <foo><b>This is text</b></foo>
  1153. @endverbatim
  1154. then it will not change "This is text", but rather prefix it with a text element:
  1155. @verbatim
  1156. <foo>Hullaballoo!<b>This is text</b></foo>
  1157. @endverbatim
  1158. For this XML:
  1159. @verbatim
  1160. <foo />
  1161. @endverbatim
  1162. SetText() will generate
  1163. @verbatim
  1164. <foo>Hullaballoo!</foo>
  1165. @endverbatim
  1166. */
  1167. void SetText(const char* inText);
  1168. /// Convenience method for setting text inside an element. See SetText() for important limitations.
  1169. void SetText(int value);
  1170. /// Convenience method for setting text inside an element. See SetText() for important limitations.
  1171. void SetText(unsigned value);
  1172. /// Convenience method for setting text inside an element. See SetText() for important limitations.
  1173. void SetText(int64_t value);
  1174. /// Convenience method for setting text inside an element. See SetText() for important limitations.
  1175. void SetText(bool value);
  1176. /// Convenience method for setting text inside an element. See SetText() for important limitations.
  1177. void SetText(double value);
  1178. /// Convenience method for setting text inside an element. See SetText() for important limitations.
  1179. void SetText(float value);
  1180. /**
  1181. Convenience method to query the value of a child text node. This is probably best
  1182. shown by example. Given you have a document is this form:
  1183. @verbatim
  1184. <point>
  1185. <x>1</x>
  1186. <y>1.4</y>
  1187. </point>
  1188. @endverbatim
  1189. The QueryIntText() and similar functions provide a safe and easier way to get to the
  1190. "value" of x and y.
  1191. @verbatim
  1192. int x = 0;
  1193. float y = 0; // types of x and y are contrived for example
  1194. const XMLElement* xElement = pointElement->FirstChildElement( "x" );
  1195. const XMLElement* yElement = pointElement->FirstChildElement( "y" );
  1196. xElement->QueryIntText( &x );
  1197. yElement->QueryFloatText( &y );
  1198. @endverbatim
  1199. @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted
  1200. to the requested type, and XML_NO_TEXT_NODE if there is no child text to query.
  1201. */
  1202. XMLError QueryIntText(int* val) const;
  1203. /// See QueryIntText()
  1204. XMLError QueryUnsignedText(unsigned* val) const;
  1205. /// See QueryIntText()
  1206. XMLError QueryInt64Text(int64_t* val) const;
  1207. /// See QueryIntText()
  1208. XMLError QueryBoolText(bool* val) const;
  1209. /// See QueryIntText()
  1210. XMLError QueryDoubleText(double* val) const;
  1211. /// See QueryIntText()
  1212. XMLError QueryFloatText(float* val) const;
  1213. int IntText(int defaultValue = 0) const;
  1214. /// See QueryIntText()
  1215. unsigned UnsignedText(unsigned defaultValue = 0) const;
  1216. /// See QueryIntText()
  1217. int64_t Int64Text(int64_t defaultValue = 0) const;
  1218. /// See QueryIntText()
  1219. bool BoolText(bool defaultValue = false) const;
  1220. /// See QueryIntText()
  1221. double DoubleText(double defaultValue = 0) const;
  1222. /// See QueryIntText()
  1223. float FloatText(float defaultValue = 0) const;
  1224. // internal:
  1225. enum ElementClosingType
  1226. {
  1227. OPEN, // <foo>
  1228. CLOSED, // <foo/>
  1229. CLOSING // </foo>
  1230. };
  1231. ElementClosingType ClosingType() const { return _closingType; }
  1232. XMLNode* ShallowClone(XMLDocument* doc) const override;
  1233. bool ShallowEqual(const XMLNode* compare) const override;
  1234. protected:
  1235. char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) override;
  1236. private:
  1237. explicit XMLElement(XMLDocument* doc) : XMLNode(doc) { }
  1238. ~XMLElement() override;
  1239. XMLElement(const XMLElement&) = delete; // not supported
  1240. void operator=(const XMLElement&) = delete; // not supported
  1241. XMLAttribute* FindOrCreateAttribute(const char* name);
  1242. char* ParseAttributes(char* p, int* curLineNumPtr);
  1243. static void DeleteAttribute(XMLAttribute* attribute);
  1244. XMLAttribute* CreateAttribute();
  1245. enum { BUF_SIZE = 200 };
  1246. ElementClosingType _closingType = OPEN;
  1247. // The attribute list is ordered; there is no 'lastAttribute'
  1248. // because the list needs to be scanned for dupes before adding
  1249. // a new attribute.
  1250. XMLAttribute* _rootAttribute = nullptr;
  1251. };
  1252. enum Whitespace
  1253. {
  1254. PRESERVE_WHITESPACE,
  1255. COLLAPSE_WHITESPACE
  1256. };
  1257. /** A Document binds together all the functionality.
  1258. It can be saved, loaded, and printed to the screen.
  1259. All Nodes are connected and allocated to a Document.
  1260. If the Document is deleted, all its Nodes are also deleted.
  1261. */
  1262. class TINYXML2_LIB XMLDocument : public XMLNode
  1263. {
  1264. friend class XMLElement;
  1265. // Gives access to SetError and Push/PopDepth, but over-access for everything else.
  1266. // Wishing C++ had "internal" scope.
  1267. friend class XMLNode;
  1268. friend class XMLText;
  1269. friend class XMLComment;
  1270. friend class XMLDeclaration;
  1271. friend class XMLUnknown;
  1272. public:
  1273. /// constructor
  1274. explicit XMLDocument(bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE);
  1275. ~XMLDocument() override;
  1276. XMLDocument* ToDocument() override
  1277. {
  1278. TIXMLASSERT(this == _document);
  1279. return this;
  1280. }
  1281. const XMLDocument* ToDocument() const override
  1282. {
  1283. TIXMLASSERT(this == _document);
  1284. return this;
  1285. }
  1286. /**
  1287. Parse an XML file from a character string.
  1288. Returns XML_SUCCESS (0) on success, or an errorID.
  1289. You may optionally pass in the 'nBytes', which is the number of bytes which will be parsed.
  1290. If not specified, TinyXML-2 will assume 'xml' points to a null terminated string.
  1291. */
  1292. XMLError Parse(const char* xml, size_t len = size_t(-1));
  1293. /**
  1294. Load an XML file from disk.
  1295. Returns XML_SUCCESS (0) on success, or
  1296. an errorID.
  1297. */
  1298. XMLError LoadFile(const char* filename);
  1299. /**
  1300. Load an XML file from disk. You are responsible
  1301. for providing and closing the FILE*.
  1302. NOTE: The file should be opened as binary ("rb")
  1303. not text in order for TinyXML-2 to correctly
  1304. do newline normalization.
  1305. Returns XML_SUCCESS (0) on success, or
  1306. an errorID.
  1307. */
  1308. XMLError LoadFile(FILE* fp);
  1309. /**
  1310. Save the XML file to disk.
  1311. Returns XML_SUCCESS (0) on success, or
  1312. an errorID.
  1313. */
  1314. XMLError SaveFile(const char* filename, bool compact = false);
  1315. /**
  1316. Save the XML file to disk. You are responsible
  1317. for providing and closing the FILE*.
  1318. Returns XML_SUCCESS (0) on success, or
  1319. an errorID.
  1320. */
  1321. XMLError SaveFile(FILE* fp, bool compact = false);
  1322. bool ProcessEntities() const { return _processEntities; }
  1323. Whitespace WhitespaceMode() const { return _whitespaceMode; }
  1324. /// Returns true if this document has a leading Byte Order Mark of UTF8.
  1325. bool HasBOM() const { return _writeBOM; }
  1326. /// Sets whether to write the BOM when writing the file.
  1327. void SetBOM(const bool useBOM) { _writeBOM = useBOM; }
  1328. /// Return the root element of DOM. Equivalent to FirstChildElement(). To get the first node, use FirstChild().
  1329. XMLElement* RootElement() { return FirstChildElement(); }
  1330. const XMLElement* RootElement() const { return FirstChildElement(); }
  1331. /** Print the Document. If the Printer is not provided, it will
  1332. print to stdout. If you provide Printer, this can print to a file:
  1333. @verbatim
  1334. XMLPrinter printer( fp );
  1335. doc.Print( &printer );
  1336. @endverbatim
  1337. Or you can use a printer to print to memory:
  1338. @verbatim
  1339. XMLPrinter printer;
  1340. doc.Print( &printer );
  1341. // printer.CStr() has a const char* to the XML
  1342. @endverbatim
  1343. */
  1344. void Print(XMLPrinter* streamer = nullptr) const;
  1345. bool Accept(XMLVisitor* visitor) const override;
  1346. /// Create a new Element associated with this Document. The memory for the Element is managed by the Document.
  1347. XMLElement* NewElement(const char* name);
  1348. /// Create a new Comment associated with this Document. The memory for the Comment is managed by the Document.
  1349. XMLComment* NewComment(const char* str);
  1350. /// Create a new Text associated with this Document. The memory for the Text is managed by the Document. */
  1351. XMLText* NewText(const char* str);
  1352. /**
  1353. Create a new Declaration associated with this Document. The memory for the object is managed by the Document.
  1354. If the 'text' param is null, the standard declaration is used.:
  1355. @verbatim
  1356. <?xml version="1.0" encoding="UTF-8"?>
  1357. @endverbatim
  1358. */
  1359. XMLDeclaration* NewDeclaration(const char* str = nullptr);
  1360. /// Create a new Unknown associated with this Document. The memory for the object is managed by the Document.
  1361. XMLUnknown* NewUnknown(const char* str);
  1362. /// Delete a node associated with this document. It will be unlinked from the DOM.
  1363. void DeleteNode(XMLNode* node);
  1364. void ClearError() { SetError(XML_SUCCESS, 0, nullptr); }
  1365. /// Return true if there was an error parsing the document.
  1366. bool Error() const { return _errorID != XML_SUCCESS; }
  1367. /// Return the errorID.
  1368. XMLError ErrorID() const { return _errorID; }
  1369. const char* ErrorName() const { return ErrorIDToName(_errorID); }
  1370. static const char* ErrorIDToName(XMLError errorID);
  1371. /** Returns a "long form" error description. A hopefully helpful
  1372. diagnostic with location, line number, and/or additional info.
  1373. */
  1374. const char* ErrorStr() const { return _errorStr.Empty() ? "" : _errorStr.GetStr(); }
  1375. /// A (trivial) utility function that prints the ErrorStr() to stdout.
  1376. void PrintError() const { printf("%s\n", ErrorStr()); }
  1377. /// Return the line where the error occurred, or zero if unknown.
  1378. int ErrorLineNum() const { return _errorLineNum; }
  1379. /// Clear the document, resetting it to the initial state.
  1380. void Clear();
  1381. /**
  1382. Copies this document to a target document.
  1383. The target will be completely cleared before the copy.
  1384. If you want to copy a sub-tree, see XMLNode::DeepClone().
  1385. NOTE: that the 'target' must be non-null.
  1386. */
  1387. void DeepCopy(XMLDocument* target) const;
  1388. // internal
  1389. char* Identify(char* p, XMLNode** node);
  1390. // internal
  1391. void MarkInUse(XMLNode* node);
  1392. XMLNode* ShallowClone(XMLDocument* /*document*/) const override { return nullptr; }
  1393. bool ShallowEqual(const XMLNode* /*compare*/) const override { return false; }
  1394. private:
  1395. XMLDocument(const XMLDocument&) = delete; // not supported
  1396. void operator=(const XMLDocument&) = delete; // not supported
  1397. bool _writeBOM = false;
  1398. bool _processEntities = false;
  1399. XMLError _errorID = XML_SUCCESS;
  1400. Whitespace _whitespaceMode;
  1401. mutable StrPair _errorStr;
  1402. int _errorLineNum = 0;
  1403. char* _charBuffer = nullptr;
  1404. int _parseCurLineNum = 0;
  1405. int _parsingDepth = 0;
  1406. // Memory tracking does add some overhead.
  1407. // However, the code assumes that you don't
  1408. // have a bunch of unlinked nodes around.
  1409. // Therefore it takes less memory to track
  1410. // in the document vs. a linked list in the XMLNode,
  1411. // and the performance is the same.
  1412. DynArray<XMLNode*, 10> _unlinked;
  1413. MemPoolT<sizeof(XMLElement)> _elementPool;
  1414. MemPoolT<sizeof(XMLAttribute)> _attributePool;
  1415. MemPoolT<sizeof(XMLText)> _textPool;
  1416. MemPoolT<sizeof(XMLComment)> _commentPool;
  1417. static const char* _errorNames[XML_ERROR_COUNT];
  1418. void Parse();
  1419. void SetError(XMLError error, int lineNum, const char* format, ...);
  1420. // Something of an obvious security hole, once it was discovered.
  1421. // Either an ill-formed XML or an excessively deep one can overflow
  1422. // the stack. Track stack depth, and error out if needed.
  1423. class DepthTracker
  1424. {
  1425. public:
  1426. explicit DepthTracker(XMLDocument* document)
  1427. {
  1428. this->_document = document;
  1429. document->PushDepth();
  1430. }
  1431. ~DepthTracker() { _document->PopDepth(); }
  1432. private:
  1433. XMLDocument* _document;
  1434. };
  1435. void PushDepth();
  1436. void PopDepth();
  1437. template <class NodeType, int PoolElementSize>
  1438. NodeType* CreateUnlinkedNode(MemPoolT<PoolElementSize>& pool);
  1439. };
  1440. template <class NodeType, int PoolElementSize>
  1441. NodeType* XMLDocument::CreateUnlinkedNode(MemPoolT<PoolElementSize>& pool)
  1442. {
  1443. TIXMLASSERT(sizeof(NodeType) == PoolElementSize);
  1444. TIXMLASSERT(sizeof(NodeType) == pool.ItemSize());
  1445. NodeType* returnNode = new(pool.Alloc()) NodeType(this);
  1446. TIXMLASSERT(returnNode);
  1447. returnNode->_memPool = &pool;
  1448. _unlinked.Push(returnNode);
  1449. return returnNode;
  1450. }
  1451. /**
  1452. A XMLHandle is a class that wraps a node pointer with null checks; this is
  1453. an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2
  1454. DOM structure. It is a separate utility class.
  1455. Take an example:
  1456. @verbatim
  1457. <Document>
  1458. <Element attributeA = "valueA">
  1459. <Child attributeB = "value1" />
  1460. <Child attributeB = "value2" />
  1461. </Element>
  1462. </Document>
  1463. @endverbatim
  1464. Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
  1465. easy to write a *lot* of code that looks like:
  1466. @verbatim
  1467. XMLElement* root = document.FirstChildElement( "Document" );
  1468. if ( root )
  1469. {
  1470. XMLElement* element = root->FirstChildElement( "Element" );
  1471. if ( element )
  1472. {
  1473. XMLElement* child = element->FirstChildElement( "Child" );
  1474. if ( child )
  1475. {
  1476. XMLElement* child2 = child->NextSiblingElement( "Child" );
  1477. if ( child2 )
  1478. {
  1479. // Finally do something useful.
  1480. @endverbatim
  1481. And that doesn't even cover "else" cases. XMLHandle addresses the verbosity
  1482. of such code. A XMLHandle checks for null pointers so it is perfectly safe
  1483. and correct to use:
  1484. @verbatim
  1485. XMLHandle docHandle( &document );
  1486. XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement();
  1487. if ( child2 )
  1488. {
  1489. // do something useful
  1490. @endverbatim
  1491. Which is MUCH more concise and useful.
  1492. It is also safe to copy handles - internally they are nothing more than node pointers.
  1493. @verbatim
  1494. XMLHandle handleCopy = handle;
  1495. @endverbatim
  1496. See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects.
  1497. */
  1498. class TINYXML2_LIB XMLHandle
  1499. {
  1500. public:
  1501. /// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
  1502. explicit XMLHandle(XMLNode* node) : _node(node) { }
  1503. /// Create a handle from a node.
  1504. explicit XMLHandle(XMLNode& node) : _node(&node) { }
  1505. /// Copy constructor
  1506. XMLHandle(const XMLHandle& ref) : _node(ref._node) { }
  1507. /// Assignment
  1508. XMLHandle& operator=(const XMLHandle& ref)
  1509. {
  1510. _node = ref._node;
  1511. return *this;
  1512. }
  1513. /// Get the first child of this handle.
  1514. XMLHandle FirstChild() { return XMLHandle(_node ? _node->FirstChild() : nullptr); }
  1515. /// Get the first child element of this handle.
  1516. XMLHandle FirstChildElement(const char* name = nullptr) { return XMLHandle(_node ? _node->FirstChildElement(name) : nullptr); }
  1517. /// Get the last child of this handle.
  1518. XMLHandle LastChild() { return XMLHandle(_node ? _node->LastChild() : nullptr); }
  1519. /// Get the last child element of this handle.
  1520. XMLHandle LastChildElement(const char* name = nullptr) { return XMLHandle(_node ? _node->LastChildElement(name) : nullptr); }
  1521. /// Get the previous sibling of this handle.
  1522. XMLHandle PreviousSibling() { return XMLHandle(_node ? _node->PreviousSibling() : nullptr); }
  1523. /// Get the previous sibling element of this handle.
  1524. XMLHandle PreviousSiblingElement(const char* name = nullptr) { return XMLHandle(_node ? _node->PreviousSiblingElement(name) : nullptr); }
  1525. /// Get the next sibling of this handle.
  1526. XMLHandle NextSibling() { return XMLHandle(_node ? _node->NextSibling() : nullptr); }
  1527. /// Get the next sibling element of this handle.
  1528. XMLHandle NextSiblingElement(const char* name = nullptr) { return XMLHandle(_node ? _node->NextSiblingElement(name) : nullptr); }
  1529. /// Safe cast to XMLNode. This can return null.
  1530. XMLNode* ToNode() { return _node; }
  1531. /// Safe cast to XMLElement. This can return null.
  1532. XMLElement* ToElement() { return (_node ? _node->ToElement() : nullptr); }
  1533. /// Safe cast to XMLText. This can return null.
  1534. XMLText* ToText() { return (_node ? _node->ToText() : nullptr); }
  1535. /// Safe cast to XMLUnknown. This can return null.
  1536. XMLUnknown* ToUnknown() { return (_node ? _node->ToUnknown() : nullptr); }
  1537. /// Safe cast to XMLDeclaration. This can return null.
  1538. XMLDeclaration* ToDeclaration() { return (_node ? _node->ToDeclaration() : nullptr); }
  1539. private:
  1540. XMLNode* _node;
  1541. };
  1542. /**
  1543. A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the
  1544. same in all regards, except for the 'const' qualifiers. See XMLHandle for API.
  1545. */
  1546. class TINYXML2_LIB XMLConstHandle
  1547. {
  1548. public:
  1549. explicit XMLConstHandle(const XMLNode* node) : _node(node) { }
  1550. explicit XMLConstHandle(const XMLNode& node) : _node(&node) { }
  1551. XMLConstHandle(const XMLConstHandle& ref) : _node(ref._node) { }
  1552. XMLConstHandle& operator=(const XMLConstHandle& ref)
  1553. {
  1554. _node = ref._node;
  1555. return *this;
  1556. }
  1557. XMLConstHandle FirstChild() const { return XMLConstHandle(_node ? _node->FirstChild() : nullptr); }
  1558. XMLConstHandle FirstChildElement(const char* name = nullptr) const { return XMLConstHandle(_node ? _node->FirstChildElement(name) : nullptr); }
  1559. XMLConstHandle LastChild() const { return XMLConstHandle(_node ? _node->LastChild() : nullptr); }
  1560. XMLConstHandle LastChildElement(const char* name = nullptr) const { return XMLConstHandle(_node ? _node->LastChildElement(name) : nullptr); }
  1561. XMLConstHandle PreviousSibling() const { return XMLConstHandle(_node ? _node->PreviousSibling() : nullptr); }
  1562. XMLConstHandle PreviousSiblingElement(const char* name = nullptr) const
  1563. {
  1564. return XMLConstHandle(_node ? _node->PreviousSiblingElement(name) : nullptr);
  1565. }
  1566. XMLConstHandle NextSibling() const { return XMLConstHandle(_node ? _node->NextSibling() : nullptr); }
  1567. XMLConstHandle NextSiblingElement(const char* name = nullptr) const { return XMLConstHandle(_node ? _node->NextSiblingElement(name) : nullptr); }
  1568. const XMLNode* ToNode() const { return _node; }
  1569. const XMLElement* ToElement() const { return (_node ? _node->ToElement() : nullptr); }
  1570. const XMLText* ToText() const { return (_node ? _node->ToText() : nullptr); }
  1571. const XMLUnknown* ToUnknown() const { return (_node ? _node->ToUnknown() : nullptr); }
  1572. const XMLDeclaration* ToDeclaration() const { return (_node ? _node->ToDeclaration() : nullptr); }
  1573. private:
  1574. const XMLNode* _node;
  1575. };
  1576. /**
  1577. Printing functionality. The XMLPrinter gives you more
  1578. options than the XMLDocument::Print() method.
  1579. It can:
  1580. -# Print to memory.
  1581. -# Print to a file you provide.
  1582. -# Print XML without a XMLDocument.
  1583. Print to Memory
  1584. @verbatim
  1585. XMLPrinter printer;
  1586. doc.Print( &printer );
  1587. SomeFunction( printer.CStr() );
  1588. @endverbatim
  1589. Print to a File
  1590. You provide the file pointer.
  1591. @verbatim
  1592. XMLPrinter printer( fp );
  1593. doc.Print( &printer );
  1594. @endverbatim
  1595. Print without a XMLDocument
  1596. When loading, an XML parser is very useful. However, sometimes
  1597. when saving, it just gets in the way. The code is often set up
  1598. for streaming, and constructing the DOM is just overhead.
  1599. The Printer supports the streaming case. The following code
  1600. prints out a trivially simple XML file without ever creating
  1601. an XML document.
  1602. @verbatim
  1603. XMLPrinter printer( fp );
  1604. printer.OpenElement( "foo" );
  1605. printer.PushAttribute( "foo", "bar" );
  1606. printer.CloseElement();
  1607. @endverbatim
  1608. */
  1609. class TINYXML2_LIB XMLPrinter : public XMLVisitor
  1610. {
  1611. public:
  1612. /** Construct the printer. If the FILE* is specified,
  1613. this will print to the FILE. Else it will print
  1614. to memory, and the result is available in CStr().
  1615. If 'compact' is set to true, then output is created
  1616. with only required whitespace and newlines.
  1617. */
  1618. explicit XMLPrinter(FILE* file = nullptr, bool compact = false, int depth = 0);
  1619. ~XMLPrinter() override {}
  1620. /** If streaming, write the BOM and declaration. */
  1621. void PushHeader(bool writeBOM, bool writeDec);
  1622. /** If streaming, start writing an element.
  1623. The element must be closed with CloseElement()
  1624. */
  1625. void OpenElement(const char* name, bool compactMode = false);
  1626. /// If streaming, add an attribute to an open element.
  1627. void PushAttribute(const char* name, const char* value);
  1628. void PushAttribute(const char* name, int value);
  1629. void PushAttribute(const char* name, unsigned value);
  1630. void PushAttribute(const char* name, int64_t value);
  1631. void PushAttribute(const char* name, bool value);
  1632. void PushAttribute(const char* name, double value);
  1633. /// If streaming, close the Element.
  1634. virtual void CloseElement(bool compactMode = false);
  1635. /// Add a text node.
  1636. void PushText(const char* text, bool cdata = false);
  1637. /// Add a text node from an integer.
  1638. void PushText(int value);
  1639. /// Add a text node from an unsigned.
  1640. void PushText(unsigned value);
  1641. /// Add a text node from an unsigned.
  1642. void PushText(int64_t value);
  1643. /// Add a text node from a bool.
  1644. void PushText(bool value);
  1645. /// Add a text node from a float.
  1646. void PushText(float value);
  1647. /// Add a text node from a double.
  1648. void PushText(double value);
  1649. /// Add a comment
  1650. void PushComment(const char* comment);
  1651. void PushDeclaration(const char* value);
  1652. void PushUnknown(const char* value);
  1653. bool VisitEnter(const XMLDocument& /*doc*/) override;
  1654. bool VisitExit(const XMLDocument& /*doc*/) override { return true; }
  1655. bool VisitEnter(const XMLElement& element, const XMLAttribute* attribute) override;
  1656. bool VisitExit(const XMLElement& element) override;
  1657. bool Visit(const XMLText& text) override;
  1658. bool Visit(const XMLComment& comment) override;
  1659. bool Visit(const XMLDeclaration& declaration) override;
  1660. bool Visit(const XMLUnknown& unknown) override;
  1661. /**
  1662. If in print to memory mode, return a pointer to
  1663. the XML file in memory.
  1664. */
  1665. const char* CStr() const { return _buffer.Mem(); }
  1666. /**
  1667. If in print to memory mode, return the size
  1668. of the XML file in memory. (Note the size returned
  1669. includes the terminating null.)
  1670. */
  1671. int CStrSize() const { return _buffer.Size(); }
  1672. /**
  1673. If in print to memory mode, reset the buffer to the
  1674. beginning.
  1675. */
  1676. void ClearBuffer()
  1677. {
  1678. _buffer.Clear();
  1679. _buffer.Push(0);
  1680. _firstElement = true;
  1681. }
  1682. protected:
  1683. virtual bool CompactMode(const XMLElement& /*element*/) { return _compactMode; }
  1684. /** Prints out the space before an element. You may override to change
  1685. the space and tabs used. A PrintSpace() override should call Print().
  1686. */
  1687. virtual void PrintSpace(const int depth) { for (int i = 0; i < depth; ++i) { Write(" "); } }
  1688. void Print(const char* format, ...);
  1689. void Write(const char* data, size_t size);
  1690. void Write(const char* data) { Write(data, strlen(data)); }
  1691. void Putc(char ch);
  1692. void SealElementIfJustOpened();
  1693. bool _elementJustOpened = false;
  1694. DynArray<const char*, 10> _stack;
  1695. private:
  1696. void PrintString(const char* p, bool restricted); // prints out, after detecting entities.
  1697. bool _firstElement = true;
  1698. FILE* _fp = nullptr;
  1699. int _depth = 0;
  1700. int _textDepth = -1;
  1701. bool _processEntities = true;
  1702. bool _compactMode = false;
  1703. enum
  1704. {
  1705. ENTITY_RANGE = 64,
  1706. BUF_SIZE = 200
  1707. };
  1708. bool _entityFlag[ENTITY_RANGE];
  1709. bool _restrictedEntityFlag[ENTITY_RANGE];
  1710. DynArray<char, 20> _buffer;
  1711. // Prohibit cloning, intentionally not implemented
  1712. XMLPrinter(const XMLPrinter&) = delete;
  1713. XMLPrinter& operator=(const XMLPrinter&) = delete;
  1714. };
  1715. } // namespace tinyxml2
  1716. #if defined(_MSC_VER)
  1717. # pragma warning(pop)
  1718. #endif
  1719. #endif // TINYXML2_INCLUDED