tinyxml2.h 55 KB

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