tinyxml2.h 46 KB

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