tinyxml2.h 45 KB

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