tinyxml2.h 58 KB

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