tinyxml2.h 63 KB

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