1
0

tinyxml2.h 17 KB

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