tinyxml2.h 58 KB

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