tinyxml2.h 57 KB

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