tinyxml2.h 64 KB

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