tinyxml2.h 49 KB

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