tinyxml2.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. #ifndef TINYXML2_INCLUDED
  2. #define TINYXML2_INCLUDED
  3. /*
  4. TODO
  5. - const and non-const versions of API
  6. X memory pool the class construction
  7. - attribute accessors
  8. - node navigation
  9. - handles
  10. - visit pattern - change streamer?
  11. - make constructors protected
  12. - hide copy constructor
  13. - hide = operator
  14. X UTF8 support: isAlpha, etc.
  15. */
  16. #include <limits.h>
  17. #include <ctype.h>
  18. #include <stdio.h>
  19. #include <memory.h>
  20. #if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__)
  21. #ifndef DEBUG
  22. #define DEBUG
  23. #endif
  24. #endif
  25. #if defined(DEBUG)
  26. #if defined(_MSC_VER)
  27. #define TIXMLASSERT( x ) if ( !(x)) { _asm { int 3 } } //if ( !(x)) WinDebugBreak()
  28. #elif defined (ANDROID_NDK)
  29. #include <android/log.h>
  30. #define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); }
  31. #else
  32. #include <assert.h>
  33. #define TIXMLASSERT assert
  34. #endif
  35. #else
  36. #define TIXMLASSERT( x ) {}
  37. #endif
  38. namespace tinyxml2
  39. {
  40. class XMLDocument;
  41. class XMLElement;
  42. class XMLAttribute;
  43. class XMLComment;
  44. class XMLNode;
  45. class XMLText;
  46. class XMLStreamer;
  47. class StrPair
  48. {
  49. public:
  50. enum {
  51. NEEDS_ENTITY_PROCESSING = 0x01,
  52. NEEDS_NEWLINE_NORMALIZATION = 0x02,
  53. TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
  54. ATTRIBUTE_NAME = 0,
  55. ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
  56. COMMENT = NEEDS_NEWLINE_NORMALIZATION,
  57. };
  58. StrPair() : flags( 0 ), start( 0 ), end( 0 ) {}
  59. void Set( char* start, char* end, int flags ) {
  60. this->start = start; this->end = end; this->flags = flags | NEEDS_FLUSH;
  61. }
  62. const char* GetStr();
  63. bool Empty() const { return start == end; }
  64. void SetInternedStr( const char* str ) { this->start = (char*) str; this->end = 0; this->flags = 0; }
  65. char* ParseText( char* in, const char* endTag, int strFlags );
  66. char* ParseName( char* in );
  67. private:
  68. enum {
  69. NEEDS_FLUSH = 0x100
  70. };
  71. // After parsing, if *end != 0, it can be set to zero.
  72. int flags;
  73. char* start;
  74. char* end;
  75. };
  76. template <class T, int INIT>
  77. class DynArray
  78. {
  79. public:
  80. DynArray< T, INIT >()
  81. {
  82. mem = pool;
  83. allocated = INIT;
  84. size = 0;
  85. }
  86. ~DynArray()
  87. {
  88. if ( mem != pool ) {
  89. delete mem;
  90. }
  91. }
  92. void Push( T t )
  93. {
  94. EnsureCapacity( size+1 );
  95. mem[size++] = t;
  96. }
  97. T* PushArr( int count )
  98. {
  99. EnsureCapacity( size+count );
  100. T* ret = &mem[size];
  101. size += count;
  102. return ret;
  103. }
  104. T Pop() {
  105. return mem[--size];
  106. }
  107. void PopArr( int count )
  108. {
  109. TIXMLASSERT( size >= count );
  110. size -= count;
  111. }
  112. bool Empty() const { return size == 0; }
  113. T& operator[](int i) { TIXMLASSERT( i>= 0 && i < size ); return mem[i]; }
  114. const T& operator[](int i) const { TIXMLASSERT( i>= 0 && i < size ); return mem[i]; }
  115. int Size() const { return size; }
  116. const T* Mem() const { return mem; }
  117. T* Mem() { return mem; }
  118. private:
  119. void EnsureCapacity( int cap ) {
  120. if ( cap > allocated ) {
  121. int newAllocated = cap * 2;
  122. T* newMem = new T[newAllocated];
  123. memcpy( newMem, mem, sizeof(T)*size ); // warning: not using constructors, only works for PODs
  124. if ( mem != pool ) delete [] mem;
  125. mem = newMem;
  126. allocated = newAllocated;
  127. }
  128. }
  129. T* mem;
  130. T pool[INIT];
  131. int allocated; // objects allocated
  132. int size; // number objects in use
  133. };
  134. class MemPool
  135. {
  136. public:
  137. MemPool() {}
  138. virtual ~MemPool() {}
  139. virtual int ItemSize() const = 0;
  140. virtual void* Alloc() = 0;
  141. virtual void Free( void* ) = 0;
  142. };
  143. template< int SIZE >
  144. class MemPoolT : public MemPool
  145. {
  146. public:
  147. MemPoolT() : root(0), currentAllocs(0), nAllocs(0), maxAllocs(0) {}
  148. ~MemPoolT() {
  149. // Delete the blocks.
  150. for( int i=0; i<blockPtrs.Size(); ++i ) {
  151. delete blockPtrs[i];
  152. }
  153. }
  154. virtual int ItemSize() const { return SIZE; }
  155. int CurrentAllocs() const { return currentAllocs; }
  156. virtual void* Alloc() {
  157. if ( !root ) {
  158. // Need a new block.
  159. Block* block = new Block();
  160. blockPtrs.Push( block );
  161. for( int i=0; i<COUNT-1; ++i ) {
  162. block->chunk[i].next = &block->chunk[i+1];
  163. }
  164. block->chunk[COUNT-1].next = 0;
  165. root = block->chunk;
  166. }
  167. void* result = root;
  168. root = root->next;
  169. ++currentAllocs;
  170. if ( currentAllocs > maxAllocs ) maxAllocs = currentAllocs;
  171. nAllocs++;
  172. return result;
  173. }
  174. virtual void Free( void* mem ) {
  175. if ( !mem ) return;
  176. --currentAllocs;
  177. Chunk* chunk = (Chunk*)mem;
  178. memset( chunk, 0xfe, sizeof(Chunk) );
  179. chunk->next = root;
  180. root = chunk;
  181. }
  182. void Trace( const char* name ) {
  183. printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n",
  184. name, maxAllocs, maxAllocs*SIZE/1024, currentAllocs, SIZE, nAllocs, blockPtrs.Size() );
  185. }
  186. private:
  187. enum { COUNT = 1024/SIZE };
  188. union Chunk {
  189. Chunk* next;
  190. char mem[SIZE];
  191. };
  192. struct Block {
  193. Chunk chunk[COUNT];
  194. };
  195. DynArray< Block*, 10 > blockPtrs;
  196. Chunk* root;
  197. int currentAllocs;
  198. int nAllocs;
  199. int maxAllocs;
  200. };
  201. /**
  202. Implements the interface to the "Visitor pattern" (see the Accept() method.)
  203. If you call the Accept() method, it requires being passed a XMLVisitor
  204. class to handle callbacks. For nodes that contain other nodes (Document, Element)
  205. you will get called with a VisitEnter/VisitExit pair. Nodes that are always leaves
  206. are simply called with Visit().
  207. If you return 'true' from a Visit method, recursive parsing will continue. If you return
  208. false, <b>no children of this node or its sibilings</b> will be Visited.
  209. All flavors of Visit methods have a default implementation that returns 'true' (continue
  210. visiting). You need to only override methods that are interesting to you.
  211. Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting.
  212. You should never change the document from a callback.
  213. @sa XMLNode::Accept()
  214. */
  215. class XMLVisitor
  216. {
  217. public:
  218. virtual ~XMLVisitor() {}
  219. /// Visit a document.
  220. virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { return true; }
  221. /// Visit a document.
  222. virtual bool VisitExit( const XMLDocument& /*doc*/ ) { return true; }
  223. /// Visit an element.
  224. virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { return true; }
  225. /// Visit an element.
  226. virtual bool VisitExit( const XMLElement& /*element*/ ) { return true; }
  227. /// Visit a declaration
  228. //virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) { return true; }
  229. /// Visit a text node
  230. virtual bool Visit( const XMLText& /*text*/ ) { return true; }
  231. /// Visit a comment node
  232. virtual bool Visit( const XMLComment& /*comment*/ ) { return true; }
  233. /// Visit an unknown node
  234. //virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) { return true; }
  235. };
  236. class XMLUtil
  237. {
  238. public:
  239. // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't
  240. // correct, but simple, and usually works.
  241. static const char* SkipWhiteSpace( const char* p ) { while( IsUTF8Continuation(*p) || isspace( *p ) ) { ++p; } return p; }
  242. static char* SkipWhiteSpace( char* p ) { while( IsUTF8Continuation(*p) || isspace( *p ) ) { ++p; } return p; }
  243. inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) {
  244. int n = 0;
  245. if ( p == q ) {
  246. return true;
  247. }
  248. while( *p && *q && *p == *q && n<nChar ) {
  249. ++p; ++q; ++n;
  250. }
  251. if ( (n == nChar) || ( *p == 0 && *q == 0 ) ) {
  252. return true;
  253. }
  254. return false;
  255. }
  256. inline static int IsUTF8Continuation( unsigned char p ) { return p & 0x80; }
  257. inline static int IsAlphaNum( unsigned char anyByte ) { return ( anyByte < 128 ) ? isalnum( anyByte ) : 1; }
  258. inline static int IsAlpha( unsigned char anyByte ) { return ( anyByte < 128 ) ? isalpha( anyByte ) : 1; }
  259. };
  260. class XMLNode
  261. {
  262. friend class XMLDocument;
  263. friend class XMLElement;
  264. public:
  265. const XMLDocument* GetDocument() const { return document; }
  266. XMLDocument* GetDocument() { return document; }
  267. virtual XMLElement* ToElement() { return 0; }
  268. virtual XMLText* ToText() { return 0; }
  269. virtual XMLComment* ToComment() { return 0; }
  270. virtual XMLDocument* ToDocument() { return 0; }
  271. virtual const XMLElement* ToElement() const { return 0; }
  272. virtual const XMLText* ToText() const { return 0; }
  273. virtual const XMLComment* ToComment() const { return 0; }
  274. virtual const XMLDocument* ToDocument() const { return 0; }
  275. const char* Value() const { return value.GetStr(); }
  276. void SetValue( const char* val ) { value.SetInternedStr( val ); }
  277. const XMLNode* Parent() const { return parent; }
  278. XMLNode* Parent() { return parent; }
  279. /// Returns true if this node has no children.
  280. bool NoChildren() const { return !firstChild; }
  281. const XMLNode* FirstChild() const { return firstChild; }
  282. XMLNode* FirstChild() { return firstChild; }
  283. const XMLElement* FirstChildElement( const char* value=0 ) const;
  284. XMLElement* FirstChildElement( const char* value=0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->FirstChildElement( value )); }
  285. const XMLNode* LastChild() const { return lastChild; }
  286. XMLNode* LastChild() { return const_cast<XMLNode*>(const_cast<const XMLNode*>(this)->LastChild() ); }
  287. const XMLElement* LastChildElement( const char* value=0 ) const;
  288. XMLElement* LastChildElement( const char* value=0 ) { return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->LastChildElement(value) ); }
  289. const XMLNode* PreviousSibling() const { return prev; }
  290. XMLNode* PreviousSibling() { return prev; }
  291. const XMLNode* PreviousSiblingElement( const char* value=0 ) const ;
  292. XMLNode* PreviousSiblingElement( const char* value=0 ) { return const_cast<XMLNode*>(const_cast<const XMLNode*>(this)->PreviousSiblingElement( value ) ); }
  293. const XMLNode* NextSibling() const { return next; }
  294. XMLNode* NextSibling() { return next; }
  295. const XMLNode* NextSiblingElement( const char* value=0 ) const;
  296. XMLNode* NextSiblingElement( const char* value=0 ) { return const_cast<XMLNode*>(const_cast<const XMLNode*>(this)->NextSiblingElement( value ) ); }
  297. XMLNode* InsertEndChild( XMLNode* addThis );
  298. XMLNode* InsertFirstChild( XMLNode* addThis );
  299. XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis );
  300. void ClearChildren();
  301. void DeleteChild( XMLNode* node );
  302. virtual bool Accept( XMLVisitor* visitor ) const = 0;
  303. //virtual void Print( XMLStreamer* streamer );
  304. virtual char* ParseDeep( char* );
  305. void SetTextParent() { isTextParent = true; }
  306. bool IsTextParent() const { return isTextParent; }
  307. virtual bool IsClosingElement() const { return false; }
  308. protected:
  309. XMLNode( XMLDocument* );
  310. virtual ~XMLNode();
  311. XMLDocument* document;
  312. XMLNode* parent;
  313. bool isTextParent;
  314. mutable StrPair value;
  315. XMLNode* firstChild;
  316. XMLNode* lastChild;
  317. XMLNode* prev;
  318. XMLNode* next;
  319. private:
  320. MemPool* memPool;
  321. void Unlink( XMLNode* child );
  322. };
  323. class XMLText : public XMLNode
  324. {
  325. friend class XMLBase;
  326. friend class XMLDocument;
  327. public:
  328. //virtual void Print( XMLStreamer* streamer );
  329. virtual bool Accept( XMLVisitor* visitor ) const;
  330. virtual XMLText* ToText() { return this; }
  331. virtual const XMLText* ToText() const { return this; }
  332. char* ParseDeep( char* );
  333. protected:
  334. XMLText( XMLDocument* doc ) : XMLNode( doc ) {}
  335. virtual ~XMLText() {}
  336. private:
  337. };
  338. class XMLComment : public XMLNode
  339. {
  340. friend class XMLBase;
  341. friend class XMLDocument;
  342. public:
  343. virtual XMLComment* ToComment() { return this; }
  344. virtual const XMLComment* ToComment() const { return this; }
  345. virtual bool Accept( XMLVisitor* visitor ) const;
  346. char* ParseDeep( char* );
  347. protected:
  348. XMLComment( XMLDocument* doc );
  349. virtual ~XMLComment();
  350. private:
  351. };
  352. class XMLAttribute
  353. {
  354. friend class XMLElement;
  355. public:
  356. //virtual void Print( XMLStreamer* streamer );
  357. const char* Name() const { return name.GetStr(); }
  358. const char* Value() const { return value.GetStr(); }
  359. const XMLAttribute* Next() const { return next; }
  360. private:
  361. XMLAttribute( XMLElement* element ) : next( 0 ) {}
  362. virtual ~XMLAttribute() {}
  363. char* ParseDeep( char* p );
  364. mutable StrPair name;
  365. mutable StrPair value;
  366. XMLAttribute* next;
  367. MemPool* memPool;
  368. };
  369. class XMLElement : public XMLNode
  370. {
  371. friend class XMLBase;
  372. friend class XMLDocument;
  373. public:
  374. const char* Name() const { return Value(); }
  375. void SetName( const char* str ) { SetValue( str ); }
  376. virtual XMLElement* ToElement() { return this; }
  377. virtual const XMLElement* ToElement() const { return this; }
  378. virtual bool Accept( XMLVisitor* visitor ) const;
  379. const char* Attribute( const char* name ) const;
  380. int QueryIntAttribute( const char* name, int* value ) const;
  381. int QueryUnsignedAttribute( const char* name, unsigned int* value ) const;
  382. int QueryBoolAttribute( const char* name, bool* value ) const;
  383. int QueryDoubleAttribute( const char* name, double* _value ) const;
  384. int QueryFloatAttribute( const char* name, float* _value ) const;
  385. void SetAttribute( const char* name, const char* value );
  386. void SetAttribute( const char* name, int value );
  387. void SetAttribute( const char* name, unsigned value );
  388. void SetAttribute( const char* name, bool value );
  389. void SetAttribute( const char* name, double value );
  390. void RemoveAttribute( const char* name );
  391. const XMLAttribute* FirstAttribute() const { return rootAttribute; }
  392. const char* GetText() const;
  393. // internal:
  394. virtual bool IsClosingElement() const { return closing; }
  395. char* ParseDeep( char* p );
  396. protected:
  397. XMLElement( XMLDocument* doc );
  398. virtual ~XMLElement();
  399. private:
  400. char* ParseAttributes( char* p, bool *closedElement );
  401. bool closing;
  402. XMLAttribute* rootAttribute;
  403. XMLAttribute* lastAttribute; // fixme: remove
  404. };
  405. class XMLDocument : public XMLNode
  406. {
  407. friend class XMLElement;
  408. public:
  409. XMLDocument();
  410. ~XMLDocument();
  411. virtual XMLDocument* ToDocument() { return this; }
  412. virtual const XMLDocument* ToDocument() const { return this; }
  413. int Parse( const char* );
  414. int Load( const char* );
  415. int Load( FILE* );
  416. void Print( XMLStreamer* streamer=0 );
  417. virtual bool Accept( XMLVisitor* visitor ) const;
  418. XMLElement* NewElement( const char* name );
  419. enum {
  420. NO_ERROR = 0,
  421. ERROR_ELEMENT_MISMATCH,
  422. ERROR_PARSING_ELEMENT,
  423. ERROR_PARSING_ATTRIBUTE
  424. };
  425. void SetError( int error, const char* str1, const char* str2 );
  426. bool Error() const { return errorID != NO_ERROR; }
  427. int GetErrorID() const { return errorID; }
  428. const char* GetErrorStr1() const { return errorStr1; }
  429. const char* GetErrorStr2() const { return errorStr2; }
  430. char* Identify( char* p, XMLNode** node );
  431. private:
  432. XMLDocument( const XMLDocument& ); // intentionally not implemented
  433. void InitDocument();
  434. int errorID;
  435. const char* errorStr1;
  436. const char* errorStr2;
  437. char* charBuffer;
  438. MemPoolT< sizeof(XMLElement) > elementPool;
  439. MemPoolT< sizeof(XMLAttribute) > attributePool;
  440. MemPoolT< sizeof(XMLText) > textPool;
  441. MemPoolT< sizeof(XMLComment) > commentPool;
  442. };
  443. class XMLStreamer : public XMLVisitor
  444. {
  445. public:
  446. XMLStreamer( FILE* file );
  447. ~XMLStreamer() {}
  448. void OpenElement( const char* name );
  449. void PushAttribute( const char* name, const char* value );
  450. void CloseElement();
  451. void PushText( const char* text );
  452. void PushComment( const char* comment );
  453. virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { return true; }
  454. virtual bool VisitExit( const XMLDocument& /*doc*/ ) { return true; }
  455. virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute );
  456. virtual bool VisitExit( const XMLElement& element );
  457. virtual bool Visit( const XMLText& text );
  458. virtual bool Visit( const XMLComment& comment );
  459. private:
  460. void SealElement();
  461. void PrintSpace( int depth );
  462. void PrintString( const char* ); // prints out, after detecting entities.
  463. FILE* fp;
  464. int depth;
  465. bool elementJustOpened;
  466. int textDepth;
  467. enum {
  468. ENTITY_RANGE = 64
  469. };
  470. bool entityFlag[ENTITY_RANGE];
  471. DynArray< const char*, 10 > stack;
  472. };
  473. }; // tinyxml2
  474. #endif // TINYXML2_INCLUDED