tinyxml2.h 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  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. #include <cctype>
  21. #include <climits>
  22. #include <cstdio>
  23. #include <cstring>
  24. #include <cstdarg>
  25. /*
  26. TODO: intern strings instead of allocation.
  27. */
  28. /*
  29. gcc: g++ -Wall tinyxml2.cpp xmltest.cpp -o gccxmltest.exe
  30. */
  31. #if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__)
  32. #ifndef DEBUG
  33. #define DEBUG
  34. #endif
  35. #endif
  36. #if defined(DEBUG)
  37. #if defined(_MSC_VER)
  38. #define TIXMLASSERT( x ) if ( !(x)) { __debugbreak(); } //if ( !(x)) WinDebugBreak()
  39. #elif defined (ANDROID_NDK)
  40. #include <android/log.h>
  41. #define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); }
  42. #else
  43. #include <assert.h>
  44. #define TIXMLASSERT assert
  45. #endif
  46. #else
  47. #define TIXMLASSERT( x ) {}
  48. #endif
  49. #if defined(_MSC_VER) && (_MSC_VER >= 1400 )
  50. // Microsoft visual studio, version 2005 and higher.
  51. /*int _snprintf_s(
  52. char *buffer,
  53. size_t sizeOfBuffer,
  54. size_t count,
  55. const char *format [,
  56. argument] ...
  57. );*/
  58. inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) {
  59. va_list va;
  60. va_start( va, format );
  61. int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va );
  62. va_end( va );
  63. return result;
  64. }
  65. #define TIXML_SSCANF sscanf_s
  66. #else
  67. // GCC version 3 and higher
  68. //#warning( "Using sn* functions." )
  69. #define TIXML_SNPRINTF snprintf
  70. #define TIXML_SSCANF sscanf
  71. #endif
  72. static const int TIXML2_MAJOR_VERSION = 1;
  73. static const int TIXML2_MINOR_VERSION = 0;
  74. static const int TIXML2_PATCH_VERSION = 6;
  75. namespace tinyxml2
  76. {
  77. class XMLDocument;
  78. class XMLElement;
  79. class XMLAttribute;
  80. class XMLComment;
  81. class XMLNode;
  82. class XMLText;
  83. class XMLDeclaration;
  84. class XMLUnknown;
  85. class XMLPrinter;
  86. /*
  87. A class that wraps strings. Normally stores the start and end
  88. pointers into the XML file itself, and will apply normalization
  89. and entity translation if actually read. Can also store (and memory
  90. manage) a traditional char[]
  91. */
  92. class StrPair
  93. {
  94. public:
  95. enum {
  96. NEEDS_ENTITY_PROCESSING = 0x01,
  97. NEEDS_NEWLINE_NORMALIZATION = 0x02,
  98. TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
  99. TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
  100. ATTRIBUTE_NAME = 0,
  101. ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
  102. ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
  103. COMMENT = NEEDS_NEWLINE_NORMALIZATION
  104. };
  105. StrPair() : flags( 0 ), start( 0 ), end( 0 ) {}
  106. ~StrPair();
  107. void Set( char* _start, char* _end, int _flags ) {
  108. Reset();
  109. this->start = _start; this->end = _end; this->flags = _flags | NEEDS_FLUSH;
  110. }
  111. const char* GetStr();
  112. bool Empty() const { return start == end; }
  113. void SetInternedStr( const char* str ) { Reset(); this->start = const_cast<char*>(str); }
  114. void SetStr( const char* str, int flags=0 );
  115. char* ParseText( char* in, const char* endTag, int strFlags );
  116. char* ParseName( char* in );
  117. private:
  118. void Reset();
  119. enum {
  120. NEEDS_FLUSH = 0x100,
  121. NEEDS_DELETE = 0x200
  122. };
  123. // After parsing, if *end != 0, it can be set to zero.
  124. int flags;
  125. char* start;
  126. char* end;
  127. };
  128. /*
  129. A dynamic array of Plain Old Data. Doesn't support constructors, etc.
  130. Has a small initial memory pool, so that low or no usage will not
  131. cause a call to new/delete
  132. */
  133. template <class T, int INIT>
  134. class DynArray
  135. {
  136. public:
  137. DynArray< T, INIT >()
  138. {
  139. mem = pool;
  140. allocated = INIT;
  141. size = 0;
  142. }
  143. ~DynArray()
  144. {
  145. if ( mem != pool ) {
  146. delete [] mem;
  147. }
  148. }
  149. void Push( T t )
  150. {
  151. EnsureCapacity( size+1 );
  152. mem[size++] = t;
  153. }
  154. T* PushArr( int count )
  155. {
  156. EnsureCapacity( size+count );
  157. T* ret = &mem[size];
  158. size += count;
  159. return ret;
  160. }
  161. T Pop() {
  162. return mem[--size];
  163. }
  164. void PopArr( int count )
  165. {
  166. TIXMLASSERT( size >= count );
  167. size -= count;
  168. }
  169. bool Empty() const { return size == 0; }
  170. T& operator[](int i) { TIXMLASSERT( i>= 0 && i < size ); return mem[i]; }
  171. const T& operator[](int i) const { TIXMLASSERT( i>= 0 && i < size ); return mem[i]; }
  172. int Size() const { return size; }
  173. int Capacity() const { return allocated; }
  174. const T* Mem() const { return mem; }
  175. T* Mem() { return mem; }
  176. private:
  177. void EnsureCapacity( int cap ) {
  178. if ( cap > allocated ) {
  179. int newAllocated = cap * 2;
  180. T* newMem = new T[newAllocated];
  181. memcpy( newMem, mem, sizeof(T)*size ); // warning: not using constructors, only works for PODs
  182. if ( mem != pool ) delete [] mem;
  183. mem = newMem;
  184. allocated = newAllocated;
  185. }
  186. }
  187. T* mem;
  188. T pool[INIT];
  189. int allocated; // objects allocated
  190. int size; // number objects in use
  191. };
  192. /*
  193. Parent virtual class of a pool for fast allocation
  194. and deallocation of objects.
  195. */
  196. class MemPool
  197. {
  198. public:
  199. MemPool() {}
  200. virtual ~MemPool() {}
  201. virtual int ItemSize() const = 0;
  202. virtual void* Alloc() = 0;
  203. virtual void Free( void* ) = 0;
  204. };
  205. /*
  206. Template child class to create pools of the correct type.
  207. */
  208. template< int SIZE >
  209. class MemPoolT : public MemPool
  210. {
  211. public:
  212. MemPoolT() : root(0), currentAllocs(0), nAllocs(0), maxAllocs(0) {}
  213. ~MemPoolT() {
  214. // Delete the blocks.
  215. for( int i=0; i<blockPtrs.Size(); ++i ) {
  216. delete blockPtrs[i];
  217. }
  218. }
  219. virtual int ItemSize() const { return SIZE; }
  220. int CurrentAllocs() const { return currentAllocs; }
  221. virtual void* Alloc() {
  222. if ( !root ) {
  223. // Need a new block.
  224. Block* block = new Block();
  225. blockPtrs.Push( block );
  226. for( int i=0; i<COUNT-1; ++i ) {
  227. block->chunk[i].next = &block->chunk[i+1];
  228. }
  229. block->chunk[COUNT-1].next = 0;
  230. root = block->chunk;
  231. }
  232. void* result = root;
  233. root = root->next;
  234. ++currentAllocs;
  235. if ( currentAllocs > maxAllocs ) maxAllocs = currentAllocs;
  236. nAllocs++;
  237. return result;
  238. }
  239. virtual void Free( void* mem ) {
  240. if ( !mem ) return;
  241. --currentAllocs;
  242. Chunk* chunk = (Chunk*)mem;
  243. #ifdef DEBUG
  244. memset( chunk, 0xfe, sizeof(Chunk) );
  245. #endif
  246. chunk->next = root;
  247. root = chunk;
  248. }
  249. void Trace( const char* name ) {
  250. printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n",
  251. name, maxAllocs, maxAllocs*SIZE/1024, currentAllocs, SIZE, nAllocs, blockPtrs.Size() );
  252. }
  253. private:
  254. enum { COUNT = 1024/SIZE };
  255. union Chunk {
  256. Chunk* next;
  257. char mem[SIZE];
  258. };
  259. struct Block {
  260. Chunk chunk[COUNT];
  261. };
  262. DynArray< Block*, 10 > blockPtrs;
  263. Chunk* root;
  264. int currentAllocs;
  265. int nAllocs;
  266. int maxAllocs;
  267. };
  268. /**
  269. Implements the interface to the "Visitor pattern" (see the Accept() method.)
  270. If you call the Accept() method, it requires being passed a XMLVisitor
  271. class to handle callbacks. For nodes that contain other nodes (Document, Element)
  272. you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs
  273. are simply called with Visit().
  274. If you return 'true' from a Visit method, recursive parsing will continue. If you return
  275. false, <b>no children of this node or its sibilings</b> will be visited.
  276. All flavors of Visit methods have a default implementation that returns 'true' (continue
  277. visiting). You need to only override methods that are interesting to you.
  278. Generally Accept() is called on the TiXmlDocument, although all nodes support visiting.
  279. You should never change the document from a callback.
  280. @sa XMLNode::Accept()
  281. */
  282. class XMLVisitor
  283. {
  284. public:
  285. virtual ~XMLVisitor() {}
  286. /// Visit a document.
  287. virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { return true; }
  288. /// Visit a document.
  289. virtual bool VisitExit( const XMLDocument& /*doc*/ ) { return true; }
  290. /// Visit an element.
  291. virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { return true; }
  292. /// Visit an element.
  293. virtual bool VisitExit( const XMLElement& /*element*/ ) { return true; }
  294. /// Visit a declaration.
  295. virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { return true; }
  296. /// Visit a text node.
  297. virtual bool Visit( const XMLText& /*text*/ ) { return true; }
  298. /// Visit a comment node.
  299. virtual bool Visit( const XMLComment& /*comment*/ ) { return true; }
  300. /// Visit an unknown node.
  301. virtual bool Visit( const XMLUnknown& /*unknown*/ ) { return true; }
  302. };
  303. /*
  304. Utility functionality.
  305. */
  306. class XMLUtil
  307. {
  308. public:
  309. // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't
  310. // correct, but simple, and usually works.
  311. static const char* SkipWhiteSpace( const char* p ) { while( !IsUTF8Continuation(*p) && isspace( *reinterpret_cast<const unsigned char*>(p) ) ) { ++p; } return p; }
  312. static char* SkipWhiteSpace( char* p ) { while( !IsUTF8Continuation(*p) && isspace( *reinterpret_cast<unsigned char*>(p) ) ) { ++p; } return p; }
  313. inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) {
  314. int n = 0;
  315. if ( p == q ) {
  316. return true;
  317. }
  318. while( *p && *q && *p == *q && n<nChar ) {
  319. ++p; ++q; ++n;
  320. }
  321. if ( (n == nChar) || ( *p == 0 && *q == 0 ) ) {
  322. return true;
  323. }
  324. return false;
  325. }
  326. inline static int IsUTF8Continuation( const char p ) { return p & 0x80; }
  327. inline static int IsAlphaNum( unsigned char anyByte ) { return ( anyByte < 128 ) ? isalnum( anyByte ) : 1; }
  328. inline static int IsAlpha( unsigned char anyByte ) { return ( anyByte < 128 ) ? isalpha( anyByte ) : 1; }
  329. static const char* ReadBOM( const char* p, bool* hasBOM );
  330. // p is the starting location,
  331. // the UTF-8 value of the entity will be placed in value, and length filled in.
  332. static const char* GetCharacterRef( const char* p, char* value, int* length );
  333. static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
  334. // converts primitive types to strings
  335. static void ToStr( int v, char* buffer, int bufferSize );
  336. static void ToStr( unsigned v, char* buffer, int bufferSize );
  337. static void ToStr( bool v, char* buffer, int bufferSize );
  338. static void ToStr( float v, char* buffer, int bufferSize );
  339. static void ToStr( double v, char* buffer, int bufferSize );
  340. // converts strings to primitive types
  341. static bool ToInt( const char* str, int* value );
  342. static bool ToUnsigned( const char* str, unsigned* value );
  343. static bool ToBool( const char* str, bool* value );
  344. static bool ToFloat( const char* str, float* value );
  345. static bool ToDouble( const char* str, double* value );
  346. };
  347. /** XMLNode is a base class for every object that is in the
  348. XML Document Object Model (DOM), except XMLAttributes.
  349. Nodes have siblings, a parent, and children which can
  350. be navigated. A node is always in a XMLDocument.
  351. The type of a XMLNode can be queried, and it can
  352. be cast to its more defined type.
  353. A XMLDocument allocates memory for all its Nodes.
  354. When the XMLDocument gets deleted, all its Nodes
  355. will also be deleted.
  356. @verbatim
  357. A Document can contain: Element (container or leaf)
  358. Comment (leaf)
  359. Unknown (leaf)
  360. Declaration( leaf )
  361. An Element can contain: Element (container or leaf)
  362. Text (leaf)
  363. Attributes (not on tree)
  364. Comment (leaf)
  365. Unknown (leaf)
  366. @endverbatim
  367. */
  368. class XMLNode
  369. {
  370. friend class XMLDocument;
  371. friend class XMLElement;
  372. public:
  373. /// Get the XMLDocument that owns this XMLNode.
  374. const XMLDocument* GetDocument() const { return document; }
  375. /// Get the XMLDocument that owns this XMLNode.
  376. XMLDocument* GetDocument() { return document; }
  377. virtual XMLElement* ToElement() { return 0; } ///< Safely cast to an Element, or null.
  378. virtual XMLText* ToText() { return 0; } ///< Safely cast to Text, or null.
  379. virtual XMLComment* ToComment() { return 0; } ///< Safely cast to a Comment, or null.
  380. virtual XMLDocument* ToDocument() { return 0; } ///< Safely cast to a Document, or null.
  381. virtual XMLDeclaration* ToDeclaration() { return 0; } ///< Safely cast to a Declaration, or null.
  382. virtual XMLUnknown* ToUnknown() { return 0; } ///< Safely cast to an Unknown, or null.
  383. virtual const XMLElement* ToElement() const { return 0; }
  384. virtual const XMLText* ToText() const { return 0; }
  385. virtual const XMLComment* ToComment() const { return 0; }
  386. virtual const XMLDocument* ToDocument() const { return 0; }
  387. virtual const XMLDeclaration* ToDeclaration() const { return 0; }
  388. virtual const XMLUnknown* ToUnknown() const { return 0; }
  389. /** The meaning of 'value' changes for the specific type.
  390. @verbatim
  391. Document: empty
  392. Element: name of the element
  393. Comment: the comment text
  394. Unknown: the tag contents
  395. Text: the text string
  396. @endverbatim
  397. */
  398. const char* Value() const { return value.GetStr(); }
  399. /** Set the Value of an XML node.
  400. @sa Value()
  401. */
  402. void SetValue( const char* val, bool staticMem=false );
  403. /// Get the parent of this node on the DOM.
  404. const XMLNode* Parent() const { return parent; }
  405. XMLNode* Parent() { return parent; }
  406. /// Returns true if this node has no children.
  407. bool NoChildren() const { return !firstChild; }
  408. /// Get the first child node, or null if none exists.
  409. const XMLNode* FirstChild() const { return firstChild; }
  410. XMLNode* FirstChild() { return firstChild; }
  411. /** Get the first child element, or optionally the first child
  412. element with the specified name.
  413. */
  414. const XMLElement* FirstChildElement( const char* value=0 ) const;
  415. XMLElement* FirstChildElement( const char* _value=0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->FirstChildElement( _value )); }
  416. /// Get the last child node, or null if none exists.
  417. const XMLNode* LastChild() const { return lastChild; }
  418. XMLNode* LastChild() { return const_cast<XMLNode*>(const_cast<const XMLNode*>(this)->LastChild() ); }
  419. /** Get the last child element or optionally the last child
  420. element with the specified name.
  421. */
  422. const XMLElement* LastChildElement( const char* value=0 ) const;
  423. XMLElement* LastChildElement( const char* _value=0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->LastChildElement(_value) ); }
  424. /// Get the previous (left) sibling node of this node.
  425. const XMLNode* PreviousSibling() const { return prev; }
  426. XMLNode* PreviousSibling() { return prev; }
  427. /// Get the previous (left) sibling element of this node, with an opitionally supplied name.
  428. const XMLElement* PreviousSiblingElement( const char* value=0 ) const ;
  429. XMLElement* PreviousSiblingElement( const char* _value=0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->PreviousSiblingElement( _value ) ); }
  430. /// Get the next (right) sibling node of this node.
  431. const XMLNode* NextSibling() const { return next; }
  432. XMLNode* NextSibling() { return next; }
  433. /// Get the next (right) sibling element of this node, with an opitionally supplied name.
  434. const XMLElement* NextSiblingElement( const char* value=0 ) const;
  435. XMLElement* NextSiblingElement( const char* _value=0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->NextSiblingElement( _value ) ); }
  436. /**
  437. Add a child node as the last (right) child.
  438. */
  439. XMLNode* InsertEndChild( XMLNode* addThis );
  440. XMLNode* LinkEndChild( XMLNode* addThis ) { return InsertEndChild( addThis ); }
  441. /**
  442. Add a child node as the first (left) child.
  443. */
  444. XMLNode* InsertFirstChild( XMLNode* addThis );
  445. /**
  446. Add a node after the specified child node.
  447. */
  448. XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis );
  449. /**
  450. Delete all the children of this node.
  451. */
  452. void DeleteChildren();
  453. /**
  454. Delete a child of this node.
  455. */
  456. void DeleteChild( XMLNode* node );
  457. /**
  458. Make a copy of this node, but not its children.
  459. You may pass in a Document pointer that will be
  460. the owner of the new Node. If the 'document' is
  461. null, then the node returned will be allocated
  462. from the current Document. (this->GetDocument())
  463. Note: if called on a XMLDocument, this will return null.
  464. */
  465. virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0;
  466. /**
  467. Test if 2 nodes are the same, but don't test children.
  468. The 2 nodes do not need to be in the same Document.
  469. Note: if called on a XMLDocument, this will return false.
  470. */
  471. virtual bool ShallowEqual( const XMLNode* compare ) const = 0;
  472. /** Accept a hierarchical visit of the nodes in the TinyXML DOM. Every node in the
  473. XML tree will be conditionally visited and the host will be called back
  474. via the TiXmlVisitor interface.
  475. This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse
  476. the XML for the callbacks, so the performance of TinyXML is unchanged by using this
  477. interface versus any other.)
  478. The interface has been based on ideas from:
  479. - http://www.saxproject.org/
  480. - http://c2.com/cgi/wiki?HierarchicalVisitorPattern
  481. Which are both good references for "visiting".
  482. An example of using Accept():
  483. @verbatim
  484. TiXmlPrinter printer;
  485. tinyxmlDoc.Accept( &printer );
  486. const char* xmlcstr = printer.CStr();
  487. @endverbatim
  488. */
  489. virtual bool Accept( XMLVisitor* visitor ) const = 0;
  490. // internal
  491. virtual char* ParseDeep( char*, StrPair* );
  492. protected:
  493. XMLNode( XMLDocument* );
  494. virtual ~XMLNode();
  495. XMLNode( const XMLNode& ); // not supported
  496. XMLNode& operator=( const XMLNode& ); // not supported
  497. XMLDocument* document;
  498. XMLNode* parent;
  499. mutable StrPair value;
  500. XMLNode* firstChild;
  501. XMLNode* lastChild;
  502. XMLNode* prev;
  503. XMLNode* next;
  504. private:
  505. MemPool* memPool;
  506. void Unlink( XMLNode* child );
  507. };
  508. /** XML text.
  509. Note that a text node can have child element nodes, for example:
  510. @verbatim
  511. <root>This is <b>bold</b></root>
  512. @endverbatim
  513. A text node can have 2 ways to output the next. "normal" output
  514. and CDATA. It will default to the mode it was parsed from the XML file and
  515. you generally want to leave it alone, but you can change the output mode with
  516. SetCDATA() and query it with CDATA().
  517. */
  518. class XMLText : public XMLNode
  519. {
  520. friend class XMLBase;
  521. friend class XMLDocument;
  522. public:
  523. virtual bool Accept( XMLVisitor* visitor ) const;
  524. virtual XMLText* ToText() { return this; }
  525. virtual const XMLText* ToText() const { return this; }
  526. /// Declare whether this should be CDATA or standard text.
  527. void SetCData( bool _isCData ) { this->isCData = _isCData; }
  528. /// Returns true if this is a CDATA text element.
  529. bool CData() const { return isCData; }
  530. char* ParseDeep( char*, StrPair* endTag );
  531. virtual XMLNode* ShallowClone( XMLDocument* document ) const;
  532. virtual bool ShallowEqual( const XMLNode* compare ) const;
  533. protected:
  534. XMLText( XMLDocument* doc ) : XMLNode( doc ), isCData( false ) {}
  535. virtual ~XMLText() {}
  536. XMLText( const XMLText& ); // not supported
  537. XMLText& operator=( const XMLText& ); // not supported
  538. private:
  539. bool isCData;
  540. };
  541. /** An XML Comment. */
  542. class XMLComment : public XMLNode
  543. {
  544. friend class XMLDocument;
  545. public:
  546. virtual XMLComment* ToComment() { return this; }
  547. virtual const XMLComment* ToComment() const { return this; }
  548. virtual bool Accept( XMLVisitor* visitor ) const;
  549. char* ParseDeep( char*, StrPair* endTag );
  550. virtual XMLNode* ShallowClone( XMLDocument* document ) const;
  551. virtual bool ShallowEqual( const XMLNode* compare ) const;
  552. protected:
  553. XMLComment( XMLDocument* doc );
  554. virtual ~XMLComment();
  555. XMLComment( const XMLComment& ); // not supported
  556. XMLComment& operator=( const XMLComment& ); // not supported
  557. private:
  558. };
  559. /** In correct XML the declaration is the first entry in the file.
  560. @verbatim
  561. <?xml version="1.0" standalone="yes"?>
  562. @endverbatim
  563. TinyXML2 will happily read or write files without a declaration,
  564. however.
  565. The text of the declaration isn't interpreted. It is parsed
  566. and written as a string.
  567. */
  568. class XMLDeclaration : public XMLNode
  569. {
  570. friend class XMLDocument;
  571. public:
  572. virtual XMLDeclaration* ToDeclaration() { return this; }
  573. virtual const XMLDeclaration* ToDeclaration() const { return this; }
  574. virtual bool Accept( XMLVisitor* visitor ) const;
  575. char* ParseDeep( char*, StrPair* endTag );
  576. virtual XMLNode* ShallowClone( XMLDocument* document ) const;
  577. virtual bool ShallowEqual( const XMLNode* compare ) const;
  578. protected:
  579. XMLDeclaration( XMLDocument* doc );
  580. virtual ~XMLDeclaration();
  581. XMLDeclaration( const XMLDeclaration& ); // not supported
  582. XMLDeclaration& operator=( const XMLDeclaration& ); // not supported
  583. };
  584. /** Any tag that tinyXml doesn't recognize is saved as an
  585. unknown. It is a tag of text, but should not be modified.
  586. It will be written back to the XML, unchanged, when the file
  587. is saved.
  588. DTD tags get thrown into TiXmlUnknowns.
  589. */
  590. class XMLUnknown : public XMLNode
  591. {
  592. friend class XMLDocument;
  593. public:
  594. virtual XMLUnknown* ToUnknown() { return this; }
  595. virtual const XMLUnknown* ToUnknown() const { return this; }
  596. virtual bool Accept( XMLVisitor* visitor ) const;
  597. char* ParseDeep( char*, StrPair* endTag );
  598. virtual XMLNode* ShallowClone( XMLDocument* document ) const;
  599. virtual bool ShallowEqual( const XMLNode* compare ) const;
  600. protected:
  601. XMLUnknown( XMLDocument* doc );
  602. virtual ~XMLUnknown();
  603. XMLUnknown( const XMLUnknown& ); // not supported
  604. XMLUnknown& operator=( const XMLUnknown& ); // not supported
  605. };
  606. enum {
  607. XML_NO_ERROR = 0,
  608. XML_SUCCESS = 0,
  609. XML_NO_ATTRIBUTE,
  610. XML_WRONG_ATTRIBUTE_TYPE,
  611. XML_ERROR_FILE_NOT_FOUND,
  612. XML_ERROR_FILE_COULD_NOT_BE_OPENED,
  613. XML_ERROR_FILE_READ_ERROR,
  614. XML_ERROR_ELEMENT_MISMATCH,
  615. XML_ERROR_PARSING_ELEMENT,
  616. XML_ERROR_PARSING_ATTRIBUTE,
  617. XML_ERROR_IDENTIFYING_TAG,
  618. XML_ERROR_PARSING_TEXT,
  619. XML_ERROR_PARSING_CDATA,
  620. XML_ERROR_PARSING_COMMENT,
  621. XML_ERROR_PARSING_DECLARATION,
  622. XML_ERROR_PARSING_UNKNOWN,
  623. XML_ERROR_EMPTY_DOCUMENT,
  624. XML_ERROR_MISMATCHED_ELEMENT,
  625. XML_ERROR_PARSING,
  626. XML_CAN_NOT_CONVERT_TEXT,
  627. XML_NO_TEXT_NODE
  628. };
  629. /** An attribute is a name-value pair. Elements have an arbitrary
  630. number of attributes, each with a unique name.
  631. @note The attributes are not XMLNodes. You may only query the
  632. Next() attribute in a list.
  633. */
  634. class XMLAttribute
  635. {
  636. friend class XMLElement;
  637. public:
  638. const char* Name() const { return name.GetStr(); } ///< The name of the attribute.
  639. const char* Value() const { return value.GetStr(); } ///< The value of the attribute.
  640. const XMLAttribute* Next() const { return next; } ///< The next attribute in the list.
  641. /** IntAttribute interprets the attribute as an integer, and returns the value.
  642. If the value isn't an integer, 0 will be returned. There is no error checking;
  643. use QueryIntAttribute() if you need error checking.
  644. */
  645. int IntValue() const { int i=0; QueryIntValue( &i ); return i; }
  646. /// Query as an unsigned integer. See IntAttribute()
  647. unsigned UnsignedValue() const { unsigned i=0; QueryUnsignedValue( &i ); return i; }
  648. /// Query as a boolean. See IntAttribute()
  649. bool BoolValue() const { bool b=false; QueryBoolValue( &b ); return b; }
  650. /// Query as a double. See IntAttribute()
  651. double DoubleValue() const { double d=0; QueryDoubleValue( &d ); return d; }
  652. /// Query as a float. See IntAttribute()
  653. float FloatValue() const { float f=0; QueryFloatValue( &f ); return f; }
  654. /** QueryIntAttribute interprets the attribute as an integer, and returns the value
  655. in the provided paremeter. The function will return XML_NO_ERROR on success,
  656. and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful.
  657. */
  658. int QueryIntValue( int* value ) const;
  659. /// See QueryIntAttribute
  660. int QueryUnsignedValue( unsigned int* value ) const;
  661. /// See QueryIntAttribute
  662. int QueryBoolValue( bool* value ) const;
  663. /// See QueryIntAttribute
  664. int QueryDoubleValue( double* value ) const;
  665. /// See QueryIntAttribute
  666. int QueryFloatValue( float* value ) const;
  667. /// Set the attribute to a string value.
  668. void SetAttribute( const char* value );
  669. /// Set the attribute to value.
  670. void SetAttribute( int value );
  671. /// Set the attribute to value.
  672. void SetAttribute( unsigned value );
  673. /// Set the attribute to value.
  674. void SetAttribute( bool value );
  675. /// Set the attribute to value.
  676. void SetAttribute( double value );
  677. /// Set the attribute to value.
  678. void SetAttribute( float value );
  679. private:
  680. enum { BUF_SIZE = 200 };
  681. XMLAttribute() : next( 0 ) {}
  682. virtual ~XMLAttribute() {}
  683. XMLAttribute( const XMLAttribute& ); // not supported
  684. void operator=( const XMLAttribute& ); // not supported
  685. void SetName( const char* name );
  686. char* ParseDeep( char* p, bool processEntities );
  687. mutable StrPair name;
  688. mutable StrPair value;
  689. XMLAttribute* next;
  690. MemPool* memPool;
  691. };
  692. /** The element is a container class. It has a value, the element name,
  693. and can contain other elements, text, comments, and unknowns.
  694. Elements also contain an arbitrary number of attributes.
  695. */
  696. class XMLElement : public XMLNode
  697. {
  698. friend class XMLBase;
  699. friend class XMLDocument;
  700. public:
  701. /// Get the name of an element (which is the Value() of the node.)
  702. const char* Name() const { return Value(); }
  703. /// Set the name of the element.
  704. void SetName( const char* str, bool staticMem=false ) { SetValue( str, staticMem ); }
  705. virtual XMLElement* ToElement() { return this; }
  706. virtual const XMLElement* ToElement() const { return this; }
  707. virtual bool Accept( XMLVisitor* visitor ) const;
  708. /** Given an attribute name, Attribute() returns the value
  709. for the attribute of that name, or null if none
  710. exists. For example:
  711. @verbatim
  712. const char* value = ele->Attribute( "foo" );
  713. @endverbatim
  714. The 'value' parameter is normally null. However, if specified,
  715. the attribute will only be returned if the 'name' and 'value'
  716. match. This allow you to write code:
  717. @verbatim
  718. if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar();
  719. @endverbatim
  720. rather than:
  721. @verbatim
  722. if ( ele->Attribute( "foo" ) ) {
  723. if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar();
  724. }
  725. @endverbatim
  726. */
  727. const char* Attribute( const char* name, const char* value=0 ) const;
  728. /** Given an attribute name, IntAttribute() returns the value
  729. of the attribute interpreted as an integer. 0 will be
  730. returned if there is an error. For a method with error
  731. checking, see QueryIntAttribute()
  732. */
  733. int IntAttribute( const char* name ) const { int i=0; QueryIntAttribute( name, &i ); return i; }
  734. /// See IntAttribute()
  735. unsigned UnsignedAttribute( const char* name ) const{ unsigned i=0; QueryUnsignedAttribute( name, &i ); return i; }
  736. /// See IntAttribute()
  737. bool BoolAttribute( const char* name ) const { bool b=false; QueryBoolAttribute( name, &b ); return b; }
  738. /// See IntAttribute()
  739. double DoubleAttribute( const char* name ) const { double d=0; QueryDoubleAttribute( name, &d ); return d; }
  740. /// See IntAttribute()
  741. float FloatAttribute( const char* name ) const { float f=0; QueryFloatAttribute( name, &f ); return f; }
  742. /** Given an attribute name, QueryIntAttribute() returns
  743. XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion
  744. can't be performed, or XML_NO_ATTRIBUTE if the attribute
  745. doesn't exist. If successful, the result of the conversion
  746. will be written to 'value'. If not successful, nothing will
  747. be written to 'value'. This allows you to provide default
  748. value:
  749. @verbatim
  750. int value = 10;
  751. QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10
  752. @endverbatim
  753. */
  754. int QueryIntAttribute( const char* name, int* _value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) return XML_NO_ATTRIBUTE; return a->QueryIntValue( _value ); }
  755. /// See QueryIntAttribute()
  756. int QueryUnsignedAttribute( const char* name, unsigned int* _value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) return XML_NO_ATTRIBUTE; return a->QueryUnsignedValue( _value ); }
  757. /// See QueryIntAttribute()
  758. int QueryBoolAttribute( const char* name, bool* _value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) return XML_NO_ATTRIBUTE; return a->QueryBoolValue( _value ); }
  759. /// See QueryIntAttribute()
  760. int QueryDoubleAttribute( const char* name, double* _value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) return XML_NO_ATTRIBUTE; return a->QueryDoubleValue( _value ); }
  761. /// See QueryIntAttribute()
  762. int QueryFloatAttribute( const char* name, float* _value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) return XML_NO_ATTRIBUTE; return a->QueryFloatValue( _value ); }
  763. /// Sets the named attribute to value.
  764. void SetAttribute( const char* name, const char* _value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( _value ); }
  765. /// Sets the named attribute to value.
  766. void SetAttribute( const char* name, int _value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( _value ); }
  767. /// Sets the named attribute to value.
  768. void SetAttribute( const char* name, unsigned _value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( _value ); }
  769. /// Sets the named attribute to value.
  770. void SetAttribute( const char* name, bool _value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( _value ); }
  771. /// Sets the named attribute to value.
  772. void SetAttribute( const char* name, double _value ) { XMLAttribute* a = FindOrCreateAttribute( name ); a->SetAttribute( _value ); }
  773. /**
  774. Delete an attribute.
  775. */
  776. void DeleteAttribute( const char* name );
  777. /// Return the first attribute in the list.
  778. const XMLAttribute* FirstAttribute() const { return rootAttribute; }
  779. /// Query a specific attribute in the list.
  780. const XMLAttribute* FindAttribute( const char* name ) const;
  781. /** Convenience function for easy access to the text inside an element. Although easy
  782. and concise, GetText() is limited compared to getting the TiXmlText child
  783. and accessing it directly.
  784. If the first child of 'this' is a TiXmlText, the GetText()
  785. returns the character string of the Text node, else null is returned.
  786. This is a convenient method for getting the text of simple contained text:
  787. @verbatim
  788. <foo>This is text</foo>
  789. const char* str = fooElement->GetText();
  790. @endverbatim
  791. 'str' will be a pointer to "This is text".
  792. Note that this function can be misleading. If the element foo was created from
  793. this XML:
  794. @verbatim
  795. <foo><b>This is text</b></foo>
  796. @endverbatim
  797. then the value of str would be null. The first child node isn't a text node, it is
  798. another element. From this XML:
  799. @verbatim
  800. <foo>This is <b>text</b></foo>
  801. @endverbatim
  802. GetText() will return "This is ".
  803. */
  804. const char* GetText() const;
  805. /**
  806. Convenience method to query the value of a child text node. This is probably best
  807. shown by example. Given you have a document is this form:
  808. @verbatim
  809. <point>
  810. <x>1</x>
  811. <y>1.4</y>
  812. </point>
  813. @endverbatim
  814. The QueryIntText() and similar functions provide a safe and easier way to get to the
  815. "value" of x and y.
  816. @verbatim
  817. int x = 0;
  818. float y = 0; // types of x and y are contrived for example
  819. const XMLElement* xElement = pointElement->FirstChildElement( "x" );
  820. const XMLElement* yElement = pointElement->FirstChildElement( "y" );
  821. xElement->QueryIntText( &x );
  822. yElement->QueryFloatText( &y );
  823. @endverbatim
  824. @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted
  825. to the requested type, and XML_NO_TEXT_NODE if there is no child text to query.
  826. */
  827. int QueryIntText( int* _value ) const;
  828. /// See QueryIntText()
  829. int QueryUnsignedText( unsigned* _value ) const;
  830. /// See QueryIntText()
  831. int QueryBoolText( bool* _value ) const;
  832. /// See QueryIntText()
  833. int QueryDoubleText( double* _value ) const;
  834. /// See QueryIntText()
  835. int QueryFloatText( float* _value ) const;
  836. // internal:
  837. enum {
  838. OPEN, // <foo>
  839. CLOSED, // <foo/>
  840. CLOSING // </foo>
  841. };
  842. int ClosingType() const { return closingType; }
  843. char* ParseDeep( char* p, StrPair* endTag );
  844. virtual XMLNode* ShallowClone( XMLDocument* document ) const;
  845. virtual bool ShallowEqual( const XMLNode* compare ) const;
  846. private:
  847. XMLElement( XMLDocument* doc );
  848. virtual ~XMLElement();
  849. XMLElement( const XMLElement& ); // not supported
  850. void operator=( const XMLElement& ); // not supported
  851. XMLAttribute* FindAttribute( const char* name );
  852. XMLAttribute* FindOrCreateAttribute( const char* name );
  853. //void LinkAttribute( XMLAttribute* attrib );
  854. char* ParseAttributes( char* p );
  855. int closingType;
  856. // The attribute list is ordered; there is no 'lastAttribute'
  857. // because the list needs to be scanned for dupes before adding
  858. // a new attribute.
  859. XMLAttribute* rootAttribute;
  860. };
  861. /** A Document binds together all the functionality.
  862. It can be saved, loaded, and printed to the screen.
  863. All Nodes are connected and allocated to a Document.
  864. If the Document is deleted, all its Nodes are also deleted.
  865. */
  866. class XMLDocument : public XMLNode
  867. {
  868. friend class XMLElement;
  869. public:
  870. /// constructor
  871. XMLDocument( bool processEntities = true );
  872. ~XMLDocument();
  873. virtual XMLDocument* ToDocument() { return this; }
  874. virtual const XMLDocument* ToDocument() const { return this; }
  875. /**
  876. Parse an XML file from a character string.
  877. Returns XML_NO_ERROR (0) on success, or
  878. an errorID.
  879. */
  880. int Parse( const char* xml );
  881. /**
  882. Load an XML file from disk.
  883. Returns XML_NO_ERROR (0) on success, or
  884. an errorID.
  885. */
  886. int LoadFile( const char* filename );
  887. /**
  888. Load an XML file from disk. You are responsible
  889. for providing and closing the FILE*.
  890. Returns XML_NO_ERROR (0) on success, or
  891. an errorID.
  892. */
  893. int LoadFile( FILE* );
  894. /**
  895. Save the XML file to disk.
  896. Returns XML_NO_ERROR (0) on success, or
  897. an errorID.
  898. */
  899. int SaveFile( const char* filename );
  900. /**
  901. Save the XML file to disk. You are responsible
  902. for providing and closing the FILE*.
  903. Returns XML_NO_ERROR (0) on success, or
  904. an errorID.
  905. */
  906. int SaveFile( FILE* );
  907. bool ProcessEntities() const { return processEntities; }
  908. /**
  909. Returns true if this document has a leading Byte Order Mark of UTF8.
  910. */
  911. bool HasBOM() const { return writeBOM; }
  912. /** Sets whether to write the BOM when writing the file.
  913. */
  914. void SetBOM( bool useBOM ) { writeBOM = useBOM; }
  915. /** Return the root element of DOM. Equivalent to FirstChildElement().
  916. To get the first node, use FirstChild().
  917. */
  918. XMLElement* RootElement() { return FirstChildElement(); }
  919. const XMLElement* RootElement() const { return FirstChildElement(); }
  920. /** Print the Document. If the Printer is not provided, it will
  921. print to stdout. If you provide Printer, this can print to a file:
  922. @verbatim
  923. XMLPrinter printer( fp );
  924. doc.Print( &printer );
  925. @endverbatim
  926. Or you can use a printer to print to memory:
  927. @verbatim
  928. XMLPrinter printer;
  929. doc->Print( &printer );
  930. // printer.CStr() has a const char* to the XML
  931. @endverbatim
  932. */
  933. void Print( XMLPrinter* streamer=0 );
  934. virtual bool Accept( XMLVisitor* visitor ) const;
  935. /**
  936. Create a new Element associated with
  937. this Document. The memory for the Element
  938. is managed by the Document.
  939. */
  940. XMLElement* NewElement( const char* name );
  941. /**
  942. Create a new Comment associated with
  943. this Document. The memory for the Comment
  944. is managed by the Document.
  945. */
  946. XMLComment* NewComment( const char* comment );
  947. /**
  948. Create a new Text associated with
  949. this Document. The memory for the Text
  950. is managed by the Document.
  951. */
  952. XMLText* NewText( const char* text );
  953. /**
  954. Create a new Declaration associated with
  955. this Document. The memory for the object
  956. is managed by the Document.
  957. If the 'text' param is null, the standard
  958. declaration is used.:
  959. @verbatim
  960. <?xml version="1.0" encoding="UTF-8"?>
  961. @endverbatim
  962. */
  963. XMLDeclaration* NewDeclaration( const char* text=0 );
  964. /**
  965. Create a new Unknown associated with
  966. this Document. The memory for the object
  967. is managed by the Document.
  968. */
  969. XMLUnknown* NewUnknown( const char* text );
  970. /**
  971. Delete a node associated with this document.
  972. It will be unlinked from the DOM.
  973. */
  974. void DeleteNode( XMLNode* node ) { node->parent->DeleteChild( node ); }
  975. void SetError( int error, const char* str1, const char* str2 );
  976. /// Return true if there was an error parsing the document.
  977. bool Error() const { return errorID != XML_NO_ERROR; }
  978. /// Return the errorID.
  979. int ErrorID() const { return errorID; }
  980. /// Return a possibly helpful diagnostic location or string.
  981. const char* GetErrorStr1() const { return errorStr1; }
  982. /// Return a possibly helpful secondary diagnostic location or string.
  983. const char* GetErrorStr2() const { return errorStr2; }
  984. /// If there is an error, print it to stdout.
  985. void PrintError() const;
  986. // internal
  987. char* Identify( char* p, XMLNode** node );
  988. virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { return 0; }
  989. virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { return false; }
  990. private:
  991. XMLDocument( const XMLDocument& ); // not supported
  992. void operator=( const XMLDocument& ); // not supported
  993. void InitDocument();
  994. bool writeBOM;
  995. bool processEntities;
  996. int errorID;
  997. const char* errorStr1;
  998. const char* errorStr2;
  999. char* charBuffer;
  1000. MemPoolT< sizeof(XMLElement) > elementPool;
  1001. MemPoolT< sizeof(XMLAttribute) > attributePool;
  1002. MemPoolT< sizeof(XMLText) > textPool;
  1003. MemPoolT< sizeof(XMLComment) > commentPool;
  1004. };
  1005. /**
  1006. A XMLHandle is a class that wraps a node pointer with null checks; this is
  1007. an incredibly useful thing. Note that XMLHandle is not part of the TinyXML
  1008. DOM structure. It is a separate utility class.
  1009. Take an example:
  1010. @verbatim
  1011. <Document>
  1012. <Element attributeA = "valueA">
  1013. <Child attributeB = "value1" />
  1014. <Child attributeB = "value2" />
  1015. </Element>
  1016. </Document>
  1017. @endverbatim
  1018. Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
  1019. easy to write a *lot* of code that looks like:
  1020. @verbatim
  1021. XMLElement* root = document.FirstChildElement( "Document" );
  1022. if ( root )
  1023. {
  1024. XMLElement* element = root->FirstChildElement( "Element" );
  1025. if ( element )
  1026. {
  1027. XMLElement* child = element->FirstChildElement( "Child" );
  1028. if ( child )
  1029. {
  1030. XMLElement* child2 = child->NextSiblingElement( "Child" );
  1031. if ( child2 )
  1032. {
  1033. // Finally do something useful.
  1034. @endverbatim
  1035. And that doesn't even cover "else" cases. XMLHandle addresses the verbosity
  1036. of such code. A XMLHandle checks for null pointers so it is perfectly safe
  1037. and correct to use:
  1038. @verbatim
  1039. XMLHandle docHandle( &document );
  1040. XMLElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild().NextSibling().ToElement();
  1041. if ( child2 )
  1042. {
  1043. // do something useful
  1044. @endverbatim
  1045. Which is MUCH more concise and useful.
  1046. It is also safe to copy handles - internally they are nothing more than node pointers.
  1047. @verbatim
  1048. XMLHandle handleCopy = handle;
  1049. @endverbatim
  1050. See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects.
  1051. */
  1052. class XMLHandle
  1053. {
  1054. public:
  1055. /// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
  1056. XMLHandle( XMLNode* _node ) { node = _node; }
  1057. /// Create a handle from a node.
  1058. XMLHandle( XMLNode& _node ) { node = &_node; }
  1059. /// Copy constructor
  1060. XMLHandle( const XMLHandle& ref ) { node = ref.node; }
  1061. /// Assignment
  1062. XMLHandle& operator=( const XMLHandle& ref ) { node = ref.node; return *this; }
  1063. /// Get the first child of this handle.
  1064. XMLHandle FirstChild() { return XMLHandle( node ? node->FirstChild() : 0 ); }
  1065. /// Get the first child element of this handle.
  1066. XMLHandle FirstChildElement( const char* value=0 ) { return XMLHandle( node ? node->FirstChildElement( value ) : 0 ); }
  1067. /// Get the last child of this handle.
  1068. XMLHandle LastChild() { return XMLHandle( node ? node->LastChild() : 0 ); }
  1069. /// Get the last child element of this handle.
  1070. XMLHandle LastChildElement( const char* _value=0 ) { return XMLHandle( node ? node->LastChildElement( _value ) : 0 ); }
  1071. /// Get the previous sibling of this handle.
  1072. XMLHandle PreviousSibling() { return XMLHandle( node ? node->PreviousSibling() : 0 ); }
  1073. /// Get the previous sibling element of this handle.
  1074. XMLHandle PreviousSiblingElement( const char* _value=0 ) { return XMLHandle( node ? node->PreviousSiblingElement( _value ) : 0 ); }
  1075. /// Get the next sibling of this handle.
  1076. XMLHandle NextSibling() { return XMLHandle( node ? node->NextSibling() : 0 ); }
  1077. /// Get the next sibling element of this handle.
  1078. XMLHandle NextSiblingElement( const char* _value=0 ) { return XMLHandle( node ? node->NextSiblingElement( _value ) : 0 ); }
  1079. /// Safe cast to XMLNode. This can return null.
  1080. XMLNode* ToNode() { return node; }
  1081. /// Safe cast to XMLElement. This can return null.
  1082. XMLElement* ToElement() { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); }
  1083. /// Safe cast to XMLText. This can return null.
  1084. XMLText* ToText() { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); }
  1085. /// Safe cast to XMLUnknown. This can return null.
  1086. XMLUnknown* ToUnknown() { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); }
  1087. /// Safe cast to XMLDeclaration. This can return null.
  1088. XMLDeclaration* ToDeclaration() { return ( ( node && node->ToDeclaration() ) ? node->ToDeclaration() : 0 ); }
  1089. private:
  1090. XMLNode* node;
  1091. };
  1092. /**
  1093. A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the
  1094. same in all regards, except for the 'const' qualifiers. See XMLHandle for API.
  1095. */
  1096. class XMLConstHandle
  1097. {
  1098. public:
  1099. XMLConstHandle( const XMLNode* _node ) { node = _node; }
  1100. XMLConstHandle( const XMLNode& _node ) { node = &_node; }
  1101. XMLConstHandle( const XMLConstHandle& ref ) { node = ref.node; }
  1102. XMLConstHandle& operator=( const XMLConstHandle& ref ) { node = ref.node; return *this; }
  1103. const XMLConstHandle FirstChild() const { return XMLConstHandle( node ? node->FirstChild() : 0 ); }
  1104. const XMLConstHandle FirstChildElement( const char* value=0 ) const { return XMLConstHandle( node ? node->FirstChildElement( value ) : 0 ); }
  1105. const XMLConstHandle LastChild() const { return XMLConstHandle( node ? node->LastChild() : 0 ); }
  1106. const XMLConstHandle LastChildElement( const char* _value=0 ) const { return XMLConstHandle( node ? node->LastChildElement( _value ) : 0 ); }
  1107. const XMLConstHandle PreviousSibling() const { return XMLConstHandle( node ? node->PreviousSibling() : 0 ); }
  1108. const XMLConstHandle PreviousSiblingElement( const char* _value=0 ) const { return XMLConstHandle( node ? node->PreviousSiblingElement( _value ) : 0 ); }
  1109. const XMLConstHandle NextSibling() const { return XMLConstHandle( node ? node->NextSibling() : 0 ); }
  1110. const XMLConstHandle NextSiblingElement( const char* _value=0 ) const { return XMLConstHandle( node ? node->NextSiblingElement( _value ) : 0 ); }
  1111. const XMLNode* ToNode() const { return node; }
  1112. const XMLElement* ToElement() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); }
  1113. const XMLText* ToText() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); }
  1114. const XMLUnknown* ToUnknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); }
  1115. const XMLDeclaration* ToDeclaration() const { return ( ( node && node->ToDeclaration() ) ? node->ToDeclaration() : 0 ); }
  1116. private:
  1117. const XMLNode* node;
  1118. };
  1119. /**
  1120. Printing functionality. The XMLPrinter gives you more
  1121. options than the XMLDocument::Print() method.
  1122. It can:
  1123. -# Print to memory.
  1124. -# Print to a file you provide.
  1125. -# Print XML without a XMLDocument.
  1126. Print to Memory
  1127. @verbatim
  1128. XMLPrinter printer;
  1129. doc->Print( &printer );
  1130. SomeFunction( printer.CStr() );
  1131. @endverbatim
  1132. Print to a File
  1133. You provide the file pointer.
  1134. @verbatim
  1135. XMLPrinter printer( fp );
  1136. doc.Print( &printer );
  1137. @endverbatim
  1138. Print without a XMLDocument
  1139. When loading, an XML parser is very useful. However, sometimes
  1140. when saving, it just gets in the way. The code is often set up
  1141. for streaming, and constructing the DOM is just overhead.
  1142. The Printer supports the streaming case. The following code
  1143. prints out a trivially simple XML file without ever creating
  1144. an XML document.
  1145. @verbatim
  1146. XMLPrinter printer( fp );
  1147. printer.OpenElement( "foo" );
  1148. printer.PushAttribute( "foo", "bar" );
  1149. printer.CloseElement();
  1150. @endverbatim
  1151. */
  1152. class XMLPrinter : public XMLVisitor
  1153. {
  1154. public:
  1155. /** Construct the printer. If the FILE* is specified,
  1156. this will print to the FILE. Else it will print
  1157. to memory, and the result is available in CStr().
  1158. If 'compact' is set to true, then output is created
  1159. with only required whitespace and newlines.
  1160. */
  1161. XMLPrinter( FILE* file=0, bool compact = false );
  1162. ~XMLPrinter() {}
  1163. /** If streaming, write the BOM and declaration. */
  1164. void PushHeader( bool writeBOM, bool writeDeclaration );
  1165. /** If streaming, start writing an element.
  1166. The element must be closed with CloseElement()
  1167. */
  1168. void OpenElement( const char* name );
  1169. /// If streaming, add an attribute to an open element.
  1170. void PushAttribute( const char* name, const char* value );
  1171. void PushAttribute( const char* name, int value );
  1172. void PushAttribute( const char* name, unsigned value );
  1173. void PushAttribute( const char* name, bool value );
  1174. void PushAttribute( const char* name, double value );
  1175. /// If streaming, close the Element.
  1176. void CloseElement();
  1177. /// Add a text node.
  1178. void PushText( const char* text, bool cdata=false );
  1179. /// Add a text node from an integer.
  1180. void PushText( int value );
  1181. /// Add a text node from an unsigned.
  1182. void PushText( unsigned value );
  1183. /// Add a text node from a bool.
  1184. void PushText( bool value );
  1185. /// Add a text node from a float.
  1186. void PushText( float value );
  1187. /// Add a text node from a double.
  1188. void PushText( double value );
  1189. /// Add a comment
  1190. void PushComment( const char* comment );
  1191. void PushDeclaration( const char* value );
  1192. void PushUnknown( const char* value );
  1193. virtual bool VisitEnter( const XMLDocument& /*doc*/ );
  1194. virtual bool VisitExit( const XMLDocument& /*doc*/ ) { return true; }
  1195. virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute );
  1196. virtual bool VisitExit( const XMLElement& element );
  1197. virtual bool Visit( const XMLText& text );
  1198. virtual bool Visit( const XMLComment& comment );
  1199. virtual bool Visit( const XMLDeclaration& declaration );
  1200. virtual bool Visit( const XMLUnknown& unknown );
  1201. /**
  1202. If in print to memory mode, return a pointer to
  1203. the XML file in memory.
  1204. */
  1205. const char* CStr() const { return buffer.Mem(); }
  1206. /**
  1207. If in print to memory mode, return the size
  1208. of the XML file in memory. (Note the size returned
  1209. includes the terminating null.)
  1210. */
  1211. int CStrSize() const { return buffer.Size(); }
  1212. private:
  1213. void SealElement();
  1214. void PrintSpace( int depth );
  1215. void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities.
  1216. void Print( const char* format, ... );
  1217. bool elementJustOpened;
  1218. bool firstElement;
  1219. FILE* fp;
  1220. int depth;
  1221. int textDepth;
  1222. bool processEntities;
  1223. bool compactMode;
  1224. enum {
  1225. ENTITY_RANGE = 64,
  1226. BUF_SIZE = 200
  1227. };
  1228. bool entityFlag[ENTITY_RANGE];
  1229. bool restrictedEntityFlag[ENTITY_RANGE];
  1230. DynArray< const char*, 10 > stack;
  1231. DynArray< char, 20 > buffer;
  1232. #ifdef _MSC_VER
  1233. DynArray< char, 20 > accumulator;
  1234. #endif
  1235. };
  1236. } // tinyxml2
  1237. #endif // TINYXML2_INCLUDED