tinyxml2.h 64 KB

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