tinyxml2.h 39 KB

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