tinyxml2.h 35 KB

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