tinyxml2.h 56 KB

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