tinyxml2.h 19 KB

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