tinyxml.h 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  1. /*
  2. www.sourceforge.net/projects/tinyxml
  3. Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com)
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must
  11. not claim that you wrote the original software. If you use this
  12. software in a product, an acknowledgment in the product documentation
  13. would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. */
  19. #ifndef TINYXML_INCLUDED
  20. #define TINYXML_INCLUDED
  21. #ifdef _MSC_VER
  22. #pragma warning( push )
  23. #pragma warning( disable : 4530 )
  24. #pragma warning( disable : 4786 )
  25. #endif
  26. #include <ctype.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <assert.h>
  31. // Help out windows:
  32. #if defined( _DEBUG ) && !defined( DEBUG )
  33. #define DEBUG
  34. #endif
  35. #ifdef TIXML_USE_STL
  36. #include <string>
  37. #include <iostream>
  38. #include <sstream>
  39. #define TIXML_STRING std::string
  40. #else
  41. #include "tinystr.h"
  42. #define TIXML_STRING TiXmlString
  43. #endif
  44. // Deprecated library function hell. Compilers want to use the
  45. // new safe versions. This probably doesn't fully address the problem,
  46. // but it gets closer. There are too many compilers for me to fully
  47. // test. If you get compilation troubles, undefine TIXML_SAFE
  48. #define TIXML_SAFE
  49. #ifdef TIXML_SAFE
  50. #if defined(_MSC_VER) && (_MSC_VER >= 1400 )
  51. // Microsoft visual studio, version 2005 and higher.
  52. #define TIXML_SNPRINTF _snprintf_s
  53. #define TIXML_SNSCANF _snscanf_s
  54. #elif defined(_MSC_VER) && (_MSC_VER >= 1200 )
  55. // Microsoft visual studio, version 6 and higher.
  56. //#pragma message( "Using _sn* functions." )
  57. #define TIXML_SNPRINTF _snprintf
  58. #define TIXML_SNSCANF _snscanf
  59. #elif defined(__GNUC__) && (__GNUC__ >= 3 )
  60. // GCC version 3 and higher.s
  61. //#warning( "Using sn* functions." )
  62. #define TIXML_SNPRINTF snprintf
  63. #define TIXML_SNSCANF snscanf
  64. #endif
  65. #endif
  66. class TiXmlDocument;
  67. class TiXmlElement;
  68. class TiXmlComment;
  69. class TiXmlUnknown;
  70. class TiXmlAttribute;
  71. class TiXmlText;
  72. class TiXmlDeclaration;
  73. class TiXmlParsingData;
  74. const int TIXML_MAJOR_VERSION = 2;
  75. const int TIXML_MINOR_VERSION = 5;
  76. const int TIXML_PATCH_VERSION = 1;
  77. /* Internal structure for tracking location of items
  78. in the XML file.
  79. */
  80. struct TiXmlCursor
  81. {
  82. TiXmlCursor() { Clear(); }
  83. void Clear() { row = col = -1; }
  84. int row; // 0 based.
  85. int col; // 0 based.
  86. };
  87. /**
  88. If you call the Accept() method, it requires being passed a TiXmlVisitor
  89. class to handle callbacks. For nodes that contain other nodes (Document, Element)
  90. you will get called with a VisitEnter/VisitExit pair. Nodes that are always leaves
  91. are simple called with Visit().
  92. If you return 'true' from a Visit method, recursive parsing will continue. If you return
  93. false, <b>no children of this node or its sibilings</b> will be Visited.
  94. All flavors of Visit methods have a default implementation that returns 'true' (continue
  95. visiting). You need to only override methods that are interesting to you.
  96. Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting.
  97. You should never change the document from a callback.
  98. @sa TiXmlNode::Accept()
  99. */
  100. class TiXmlVisitor
  101. {
  102. public:
  103. virtual ~TiXmlVisitor() {}
  104. /// Visit a document.
  105. virtual bool VisitEnter( const TiXmlDocument& doc ) { return true; }
  106. /// Visit a document.
  107. virtual bool VisitExit( const TiXmlDocument& doc ) { return true; }
  108. /// Visit an element.
  109. virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ) { return true; }
  110. /// Visit an element.
  111. virtual bool VisitExit( const TiXmlElement& element ) { return true; }
  112. /// Visit a declaration
  113. virtual bool Visit( const TiXmlDeclaration& declaration ) { return true; }
  114. /// Visit a text node
  115. virtual bool Visit( const TiXmlText& text ) { return true; }
  116. /// Visit a comment node
  117. virtual bool Visit( const TiXmlComment& comment ) { return true; }
  118. /// Visit an unknow node
  119. virtual bool Visit( const TiXmlUnknown& unknown ) { return true; }
  120. };
  121. // Only used by Attribute::Query functions
  122. enum
  123. {
  124. TIXML_SUCCESS,
  125. TIXML_NO_ATTRIBUTE,
  126. TIXML_WRONG_TYPE
  127. };
  128. // Used by the parsing routines.
  129. enum TiXmlEncoding
  130. {
  131. TIXML_ENCODING_UNKNOWN,
  132. TIXML_ENCODING_UTF8,
  133. TIXML_ENCODING_LEGACY
  134. };
  135. const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN;
  136. /** TiXmlBase is a base class for every class in TinyXml.
  137. It does little except to establish that TinyXml classes
  138. can be printed and provide some utility functions.
  139. In XML, the document and elements can contain
  140. other elements and other types of nodes.
  141. @verbatim
  142. A Document can contain: Element (container or leaf)
  143. Comment (leaf)
  144. Unknown (leaf)
  145. Declaration( leaf )
  146. An Element can contain: Element (container or leaf)
  147. Text (leaf)
  148. Attributes (not on tree)
  149. Comment (leaf)
  150. Unknown (leaf)
  151. A Decleration contains: Attributes (not on tree)
  152. @endverbatim
  153. */
  154. class TiXmlBase
  155. {
  156. friend class TiXmlNode;
  157. friend class TiXmlElement;
  158. friend class TiXmlDocument;
  159. public:
  160. TiXmlBase() : userData(0) {}
  161. virtual ~TiXmlBase() {}
  162. /** All TinyXml classes can print themselves to a filestream
  163. or the string class (TiXmlString in non-STL mode, std::string
  164. in STL mode.) Either or both cfile and str can be null.
  165. This is a formatted print, and will insert
  166. tabs and newlines.
  167. (For an unformatted stream, use the << operator.)
  168. */
  169. virtual void Print( FILE* cfile, int depth ) const = 0;
  170. /** The world does not agree on whether white space should be kept or
  171. not. In order to make everyone happy, these global, static functions
  172. are provided to set whether or not TinyXml will condense all white space
  173. into a single space or not. The default is to condense. Note changing this
  174. value is not thread safe.
  175. */
  176. static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; }
  177. /// Return the current white space setting.
  178. static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; }
  179. /** Return the position, in the original source file, of this node or attribute.
  180. The row and column are 1-based. (That is the first row and first column is
  181. 1,1). If the returns values are 0 or less, then the parser does not have
  182. a row and column value.
  183. Generally, the row and column value will be set when the TiXmlDocument::Load(),
  184. TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set
  185. when the DOM was created from operator>>.
  186. The values reflect the initial load. Once the DOM is modified programmatically
  187. (by adding or changing nodes and attributes) the new values will NOT update to
  188. reflect changes in the document.
  189. There is a minor performance cost to computing the row and column. Computation
  190. can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value.
  191. @sa TiXmlDocument::SetTabSize()
  192. */
  193. int Row() const { return location.row + 1; }
  194. int Column() const { return location.col + 1; } ///< See Row()
  195. void SetUserData( void* user ) { userData = user; } ///< Set a pointer to arbitrary user data.
  196. void* GetUserData() { return userData; } ///< Get a pointer to arbitrary user data.
  197. const void* GetUserData() const { return userData; } ///< Get a pointer to arbitrary user data.
  198. // Table that returs, for a given lead byte, the total number of bytes
  199. // in the UTF-8 sequence.
  200. static const int utf8ByteTable[256];
  201. virtual const char* Parse( const char* p,
  202. TiXmlParsingData* data,
  203. TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0;
  204. enum
  205. {
  206. TIXML_NO_ERROR = 0,
  207. TIXML_ERROR,
  208. TIXML_ERROR_OPENING_FILE,
  209. TIXML_ERROR_OUT_OF_MEMORY,
  210. TIXML_ERROR_PARSING_ELEMENT,
  211. TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME,
  212. TIXML_ERROR_READING_ELEMENT_VALUE,
  213. TIXML_ERROR_READING_ATTRIBUTES,
  214. TIXML_ERROR_PARSING_EMPTY,
  215. TIXML_ERROR_READING_END_TAG,
  216. TIXML_ERROR_PARSING_UNKNOWN,
  217. TIXML_ERROR_PARSING_COMMENT,
  218. TIXML_ERROR_PARSING_DECLARATION,
  219. TIXML_ERROR_DOCUMENT_EMPTY,
  220. TIXML_ERROR_EMBEDDED_NULL,
  221. TIXML_ERROR_PARSING_CDATA,
  222. TIXML_ERROR_DOCUMENT_TOP_ONLY,
  223. TIXML_ERROR_STRING_COUNT
  224. };
  225. protected:
  226. static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding );
  227. inline static bool IsWhiteSpace( char c )
  228. {
  229. return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' );
  230. }
  231. inline static bool IsWhiteSpace( int c )
  232. {
  233. if ( c < 256 )
  234. return IsWhiteSpace( (char) c );
  235. return false; // Again, only truly correct for English/Latin...but usually works.
  236. }
  237. #ifdef TIXML_USE_STL
  238. static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag );
  239. static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag );
  240. #endif
  241. /* Reads an XML name into the string provided. Returns
  242. a pointer just past the last character of the name,
  243. or 0 if the function has an error.
  244. */
  245. static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding );
  246. /* Reads text. Returns a pointer past the given end tag.
  247. Wickedly complex options, but it keeps the (sensitive) code in one place.
  248. */
  249. static const char* ReadText( const char* in, // where to start
  250. TIXML_STRING* text, // the string read
  251. bool ignoreWhiteSpace, // whether to keep the white space
  252. const char* endTag, // what ends this text
  253. bool ignoreCase, // whether to ignore case in the end tag
  254. TiXmlEncoding encoding ); // the current encoding
  255. // If an entity has been found, transform it into a character.
  256. static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding );
  257. // Get a character, while interpreting entities.
  258. // The length can be from 0 to 4 bytes.
  259. inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding )
  260. {
  261. assert( p );
  262. if ( encoding == TIXML_ENCODING_UTF8 )
  263. {
  264. *length = utf8ByteTable[ *((const unsigned char*)p) ];
  265. assert( *length >= 0 && *length < 5 );
  266. }
  267. else
  268. {
  269. *length = 1;
  270. }
  271. if ( *length == 1 )
  272. {
  273. if ( *p == '&' )
  274. return GetEntity( p, _value, length, encoding );
  275. *_value = *p;
  276. return p+1;
  277. }
  278. else if ( *length )
  279. {
  280. //strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe),
  281. // and the null terminator isn't needed
  282. for( int i=0; p[i] && i<*length; ++i ) {
  283. _value[i] = p[i];
  284. }
  285. return p + (*length);
  286. }
  287. else
  288. {
  289. // Not valid text.
  290. return 0;
  291. }
  292. }
  293. // Puts a string to a stream, expanding entities as it goes.
  294. // Note this should not contian the '<', '>', etc, or they will be transformed into entities!
  295. static void PutString( const TIXML_STRING& str, TIXML_STRING* out );
  296. // Return true if the next characters in the stream are any of the endTag sequences.
  297. // Ignore case only works for english, and should only be relied on when comparing
  298. // to English words: StringEqual( p, "version", true ) is fine.
  299. static bool StringEqual( const char* p,
  300. const char* endTag,
  301. bool ignoreCase,
  302. TiXmlEncoding encoding );
  303. static const char* errorString[ TIXML_ERROR_STRING_COUNT ];
  304. TiXmlCursor location;
  305. /// Field containing a generic user pointer
  306. void* userData;
  307. // None of these methods are reliable for any language except English.
  308. // Good for approximation, not great for accuracy.
  309. static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding );
  310. static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding );
  311. inline static int ToLower( int v, TiXmlEncoding encoding )
  312. {
  313. if ( encoding == TIXML_ENCODING_UTF8 )
  314. {
  315. if ( v < 128 ) return tolower( v );
  316. return v;
  317. }
  318. else
  319. {
  320. return tolower( v );
  321. }
  322. }
  323. static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
  324. private:
  325. TiXmlBase( const TiXmlBase& ); // not implemented.
  326. void operator=( const TiXmlBase& base ); // not allowed.
  327. struct Entity
  328. {
  329. const char* str;
  330. unsigned int strLength;
  331. char chr;
  332. };
  333. enum
  334. {
  335. NUM_ENTITY = 5,
  336. MAX_ENTITY_LENGTH = 6
  337. };
  338. static Entity entity[ NUM_ENTITY ];
  339. static bool condenseWhiteSpace;
  340. };
  341. /** The parent class for everything in the Document Object Model.
  342. (Except for attributes).
  343. Nodes have siblings, a parent, and children. A node can be
  344. in a document, or stand on its own. The type of a TiXmlNode
  345. can be queried, and it can be cast to its more defined type.
  346. */
  347. class TiXmlNode : public TiXmlBase
  348. {
  349. friend class TiXmlDocument;
  350. friend class TiXmlElement;
  351. public:
  352. #ifdef TIXML_USE_STL
  353. /** An input stream operator, for every class. Tolerant of newlines and
  354. formatting, but doesn't expect them.
  355. */
  356. friend std::istream& operator >> (std::istream& in, TiXmlNode& base);
  357. /** An output stream operator, for every class. Note that this outputs
  358. without any newlines or formatting, as opposed to Print(), which
  359. includes tabs and new lines.
  360. The operator<< and operator>> are not completely symmetric. Writing
  361. a node to a stream is very well defined. You'll get a nice stream
  362. of output, without any extra whitespace or newlines.
  363. But reading is not as well defined. (As it always is.) If you create
  364. a TiXmlElement (for example) and read that from an input stream,
  365. the text needs to define an element or junk will result. This is
  366. true of all input streams, but it's worth keeping in mind.
  367. A TiXmlDocument will read nodes until it reads a root element, and
  368. all the children of that root element.
  369. */
  370. friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base);
  371. /// Appends the XML node or attribute to a std::string.
  372. friend std::string& operator<< (std::string& out, const TiXmlNode& base );
  373. #endif
  374. /** The types of XML nodes supported by TinyXml. (All the
  375. unsupported types are picked up by UNKNOWN.)
  376. */
  377. enum NodeType
  378. {
  379. DOCUMENT,
  380. ELEMENT,
  381. COMMENT,
  382. UNKNOWN,
  383. TEXT,
  384. DECLARATION,
  385. TYPECOUNT
  386. };
  387. virtual ~TiXmlNode();
  388. /** The meaning of 'value' changes for the specific type of
  389. TiXmlNode.
  390. @verbatim
  391. Document: filename of the xml file
  392. Element: name of the element
  393. Comment: the comment text
  394. Unknown: the tag contents
  395. Text: the text string
  396. @endverbatim
  397. The subclasses will wrap this function.
  398. */
  399. const char *Value() const { return value.c_str (); }
  400. #ifdef TIXML_USE_STL
  401. /** Return Value() as a std::string. If you only use STL,
  402. this is more efficient than calling Value().
  403. Only available in STL mode.
  404. */
  405. const std::string& ValueStr() const { return value; }
  406. #endif
  407. /** Changes the value of the node. Defined as:
  408. @verbatim
  409. Document: filename of the xml file
  410. Element: name of the element
  411. Comment: the comment text
  412. Unknown: the tag contents
  413. Text: the text string
  414. @endverbatim
  415. */
  416. void SetValue(const char * _value) { value = _value;}
  417. #ifdef TIXML_USE_STL
  418. /// STL std::string form.
  419. void SetValue( const std::string& _value ) { value = _value; }
  420. #endif
  421. /// Delete all the children of this node. Does not affect 'this'.
  422. void Clear();
  423. /// One step up the DOM.
  424. TiXmlNode* Parent() { return parent; }
  425. const TiXmlNode* Parent() const { return parent; }
  426. const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children.
  427. TiXmlNode* FirstChild() { return firstChild; }
  428. const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found.
  429. /// The first child of this node with the matching 'value'. Will be null if none found.
  430. TiXmlNode* FirstChild( const char * _value ) {
  431. // Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe)
  432. // call the method, cast the return back to non-const.
  433. return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value ));
  434. }
  435. const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children.
  436. TiXmlNode* LastChild() { return lastChild; }
  437. const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children.
  438. TiXmlNode* LastChild( const char * _value ) {
  439. return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value ));
  440. }
  441. #ifdef TIXML_USE_STL
  442. const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form.
  443. TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form.
  444. const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form.
  445. TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form.
  446. #endif
  447. /** An alternate way to walk the children of a node.
  448. One way to iterate over nodes is:
  449. @verbatim
  450. for( child = parent->FirstChild(); child; child = child->NextSibling() )
  451. @endverbatim
  452. IterateChildren does the same thing with the syntax:
  453. @verbatim
  454. child = 0;
  455. while( child = parent->IterateChildren( child ) )
  456. @endverbatim
  457. IterateChildren takes the previous child as input and finds
  458. the next one. If the previous child is null, it returns the
  459. first. IterateChildren will return null when done.
  460. */
  461. const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const;
  462. TiXmlNode* IterateChildren( TiXmlNode* previous ) {
  463. return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) );
  464. }
  465. /// This flavor of IterateChildren searches for children with a particular 'value'
  466. const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const;
  467. TiXmlNode* IterateChildren( const char * _value, TiXmlNode* previous ) {
  468. return const_cast< TiXmlNode* >( const_cast< const TiXmlNode* >(this)->IterateChildren( _value, previous ) );
  469. }
  470. #ifdef TIXML_USE_STL
  471. const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
  472. TiXmlNode* IterateChildren( const std::string& _value, TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
  473. #endif
  474. /** Add a new node related to this. Adds a child past the LastChild.
  475. Returns a pointer to the new object or NULL if an error occured.
  476. */
  477. TiXmlNode* InsertEndChild( const TiXmlNode& addThis );
  478. /** Add a new node related to this. Adds a child past the LastChild.
  479. NOTE: the node to be added is passed by pointer, and will be
  480. henceforth owned (and deleted) by tinyXml. This method is efficient
  481. and avoids an extra copy, but should be used with care as it
  482. uses a different memory model than the other insert functions.
  483. @sa InsertEndChild
  484. */
  485. TiXmlNode* LinkEndChild( TiXmlNode* addThis );
  486. /** Add a new node related to this. Adds a child before the specified child.
  487. Returns a pointer to the new object or NULL if an error occured.
  488. */
  489. TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis );
  490. /** Add a new node related to this. Adds a child after the specified child.
  491. Returns a pointer to the new object or NULL if an error occured.
  492. */
  493. TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis );
  494. /** Replace a child of this node.
  495. Returns a pointer to the new object or NULL if an error occured.
  496. */
  497. TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis );
  498. /// Delete a child of this node.
  499. bool RemoveChild( TiXmlNode* removeThis );
  500. /// Navigate to a sibling node.
  501. const TiXmlNode* PreviousSibling() const { return prev; }
  502. TiXmlNode* PreviousSibling() { return prev; }
  503. /// Navigate to a sibling node.
  504. const TiXmlNode* PreviousSibling( const char * ) const;
  505. TiXmlNode* PreviousSibling( const char *_prev ) {
  506. return const_cast< TiXmlNode* >( const_cast< const TiXmlNode* >(this)->PreviousSibling( _prev ) );
  507. }
  508. #ifdef TIXML_USE_STL
  509. const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
  510. TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
  511. const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form.
  512. TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form.
  513. #endif
  514. /// Navigate to a sibling node.
  515. const TiXmlNode* NextSibling() const { return next; }
  516. TiXmlNode* NextSibling() { return next; }
  517. /// Navigate to a sibling node with the given 'value'.
  518. const TiXmlNode* NextSibling( const char * ) const;
  519. TiXmlNode* NextSibling( const char* _next ) {
  520. return const_cast< TiXmlNode* >( const_cast< const TiXmlNode* >(this)->NextSibling( _next ) );
  521. }
  522. /** Convenience function to get through elements.
  523. Calls NextSibling and ToElement. Will skip all non-Element
  524. nodes. Returns 0 if there is not another element.
  525. */
  526. const TiXmlElement* NextSiblingElement() const;
  527. TiXmlElement* NextSiblingElement() {
  528. return const_cast< TiXmlElement* >( const_cast< const TiXmlNode* >(this)->NextSiblingElement() );
  529. }
  530. /** Convenience function to get through elements.
  531. Calls NextSibling and ToElement. Will skip all non-Element
  532. nodes. Returns 0 if there is not another element.
  533. */
  534. const TiXmlElement* NextSiblingElement( const char * ) const;
  535. TiXmlElement* NextSiblingElement( const char *_next ) {
  536. return const_cast< TiXmlElement* >( const_cast< const TiXmlNode* >(this)->NextSiblingElement( _next ) );
  537. }
  538. #ifdef TIXML_USE_STL
  539. const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
  540. TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
  541. #endif
  542. /// Convenience function to get through elements.
  543. const TiXmlElement* FirstChildElement() const;
  544. TiXmlElement* FirstChildElement() {
  545. return const_cast< TiXmlElement* >( const_cast< const TiXmlNode* >(this)->FirstChildElement() );
  546. }
  547. /// Convenience function to get through elements.
  548. const TiXmlElement* FirstChildElement( const char * _value ) const;
  549. TiXmlElement* FirstChildElement( const char * _value ) {
  550. return const_cast< TiXmlElement* >( const_cast< const TiXmlNode* >(this)->FirstChildElement( _value ) );
  551. }
  552. #ifdef TIXML_USE_STL
  553. const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
  554. TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
  555. #endif
  556. /** Query the type (as an enumerated value, above) of this node.
  557. The possible types are: DOCUMENT, ELEMENT, COMMENT,
  558. UNKNOWN, TEXT, and DECLARATION.
  559. */
  560. int Type() const { return type; }
  561. /** Return a pointer to the Document this node lives in.
  562. Returns null if not in a document.
  563. */
  564. const TiXmlDocument* GetDocument() const;
  565. TiXmlDocument* GetDocument() {
  566. return const_cast< TiXmlDocument* >( const_cast< const TiXmlNode* >(this)->GetDocument() );
  567. }
  568. /// Returns true if this node has no children.
  569. bool NoChildren() const { return !firstChild; }
  570. virtual const TiXmlDocument* ToDocument() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  571. virtual const TiXmlElement* ToElement() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  572. virtual const TiXmlComment* ToComment() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  573. virtual const TiXmlUnknown* ToUnknown() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  574. virtual const TiXmlText* ToText() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  575. virtual const TiXmlDeclaration* ToDeclaration() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  576. virtual TiXmlDocument* ToDocument() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  577. virtual TiXmlElement* ToElement() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  578. virtual TiXmlComment* ToComment() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  579. virtual TiXmlUnknown* ToUnknown() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  580. virtual TiXmlText* ToText() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  581. virtual TiXmlDeclaration* ToDeclaration() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
  582. /** Create an exact duplicate of this node and return it. The memory must be deleted
  583. by the caller.
  584. */
  585. virtual TiXmlNode* Clone() const = 0;
  586. /** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the
  587. XML tree will be conditionally visited and the host will be called back
  588. via the TiXmlVisitor interface.
  589. This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse
  590. the XML for the callbacks, so the performance of TinyXML is unchanged by using this
  591. interface versus any other.)
  592. The interface has been based on ideas from:
  593. - http://www.saxproject.org/
  594. - http://c2.com/cgi/wiki?HierarchicalVisitorPattern
  595. Which are both good references for "visiting".
  596. An example of using Accept():
  597. @verbatim
  598. TiXmlPrinter printer;
  599. tinyxmlDoc.Accept( &printer );
  600. const char* xmlcstr = printer.CStr();
  601. @endverbatim
  602. */
  603. virtual bool Accept( TiXmlVisitor* visitor ) const = 0;
  604. protected:
  605. TiXmlNode( NodeType _type );
  606. // Copy to the allocated object. Shared functionality between Clone, Copy constructor,
  607. // and the assignment operator.
  608. void CopyTo( TiXmlNode* target ) const;
  609. #ifdef TIXML_USE_STL
  610. // The real work of the input operator.
  611. virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0;
  612. #endif
  613. // Figure out what is at *p, and parse it. Returns null if it is not an xml node.
  614. TiXmlNode* Identify( const char* start, TiXmlEncoding encoding );
  615. TiXmlNode* parent;
  616. NodeType type;
  617. TiXmlNode* firstChild;
  618. TiXmlNode* lastChild;
  619. TIXML_STRING value;
  620. TiXmlNode* prev;
  621. TiXmlNode* next;
  622. private:
  623. TiXmlNode( const TiXmlNode& ); // not implemented.
  624. void operator=( const TiXmlNode& base ); // not allowed.
  625. };
  626. /** An attribute is a name-value pair. Elements have an arbitrary
  627. number of attributes, each with a unique name.
  628. @note The attributes are not TiXmlNodes, since they are not
  629. part of the tinyXML document object model. There are other
  630. suggested ways to look at this problem.
  631. */
  632. class TiXmlAttribute : public TiXmlBase
  633. {
  634. friend class TiXmlAttributeSet;
  635. public:
  636. /// Construct an empty attribute.
  637. TiXmlAttribute() : TiXmlBase()
  638. {
  639. document = 0;
  640. prev = next = 0;
  641. }
  642. #ifdef TIXML_USE_STL
  643. /// std::string constructor.
  644. TiXmlAttribute( const std::string& _name, const std::string& _value )
  645. {
  646. name = _name;
  647. value = _value;
  648. document = 0;
  649. prev = next = 0;
  650. }
  651. #endif
  652. /// Construct an attribute with a name and value.
  653. TiXmlAttribute( const char * _name, const char * _value )
  654. {
  655. name = _name;
  656. value = _value;
  657. document = 0;
  658. prev = next = 0;
  659. }
  660. const char* Name() const { return name.c_str(); } ///< Return the name of this attribute.
  661. const char* Value() const { return value.c_str(); } ///< Return the value of this attribute.
  662. #ifdef TIXML_USE_STL
  663. const std::string& ValueStr() const { return value; } ///< Return the value of this attribute.
  664. #endif
  665. int IntValue() const; ///< Return the value of this attribute, converted to an integer.
  666. double DoubleValue() const; ///< Return the value of this attribute, converted to a double.
  667. // Get the tinyxml string representation
  668. const TIXML_STRING& NameTStr() const { return name; }
  669. /** QueryIntValue examines the value string. It is an alternative to the
  670. IntValue() method with richer error checking.
  671. If the value is an integer, it is stored in 'value' and
  672. the call returns TIXML_SUCCESS. If it is not
  673. an integer, it returns TIXML_WRONG_TYPE.
  674. A specialized but useful call. Note that for success it returns 0,
  675. which is the opposite of almost all other TinyXml calls.
  676. */
  677. int QueryIntValue( int* _value ) const;
  678. /// QueryDoubleValue examines the value string. See QueryIntValue().
  679. int QueryDoubleValue( double* _value ) const;
  680. void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute.
  681. void SetValue( const char* _value ) { value = _value; } ///< Set the value.
  682. void SetIntValue( int _value ); ///< Set the value from an integer.
  683. void SetDoubleValue( double _value ); ///< Set the value from a double.
  684. #ifdef TIXML_USE_STL
  685. /// STL std::string form.
  686. void SetName( const std::string& _name ) { name = _name; }
  687. /// STL std::string form.
  688. void SetValue( const std::string& _value ) { value = _value; }
  689. #endif
  690. /// Get the next sibling attribute in the DOM. Returns null at end.
  691. const TiXmlAttribute* Next() const;
  692. TiXmlAttribute* Next() {
  693. return const_cast< TiXmlAttribute* >( const_cast< const TiXmlAttribute* >(this)->Next() );
  694. }
  695. /// Get the previous sibling attribute in the DOM. Returns null at beginning.
  696. const TiXmlAttribute* Previous() const;
  697. TiXmlAttribute* Previous() {
  698. return const_cast< TiXmlAttribute* >( const_cast< const TiXmlAttribute* >(this)->Previous() );
  699. }
  700. bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; }
  701. bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; }
  702. bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; }
  703. /* Attribute parsing starts: first letter of the name
  704. returns: the next char after the value end quote
  705. */
  706. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  707. // Prints this Attribute to a FILE stream.
  708. virtual void Print( FILE* cfile, int depth ) const {
  709. Print( cfile, depth, 0 );
  710. }
  711. void Print( FILE* cfile, int depth, TIXML_STRING* str ) const;
  712. // [internal use]
  713. // Set the document pointer so the attribute can report errors.
  714. void SetDocument( TiXmlDocument* doc ) { document = doc; }
  715. private:
  716. TiXmlAttribute( const TiXmlAttribute& ); // not implemented.
  717. void operator=( const TiXmlAttribute& base ); // not allowed.
  718. TiXmlDocument* document; // A pointer back to a document, for error reporting.
  719. TIXML_STRING name;
  720. TIXML_STRING value;
  721. TiXmlAttribute* prev;
  722. TiXmlAttribute* next;
  723. };
  724. /* A class used to manage a group of attributes.
  725. It is only used internally, both by the ELEMENT and the DECLARATION.
  726. The set can be changed transparent to the Element and Declaration
  727. classes that use it, but NOT transparent to the Attribute
  728. which has to implement a next() and previous() method. Which makes
  729. it a bit problematic and prevents the use of STL.
  730. This version is implemented with circular lists because:
  731. - I like circular lists
  732. - it demonstrates some independence from the (typical) doubly linked list.
  733. */
  734. class TiXmlAttributeSet
  735. {
  736. public:
  737. TiXmlAttributeSet();
  738. ~TiXmlAttributeSet();
  739. void Add( TiXmlAttribute* attribute );
  740. void Remove( TiXmlAttribute* attribute );
  741. const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
  742. TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
  743. const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
  744. TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
  745. const TiXmlAttribute* Find( const char* _name ) const;
  746. TiXmlAttribute* Find( const char* _name ) {
  747. return const_cast< TiXmlAttribute* >( const_cast< const TiXmlAttributeSet* >(this)->Find( _name ) );
  748. }
  749. #ifdef TIXML_USE_STL
  750. const TiXmlAttribute* Find( const std::string& _name ) const;
  751. TiXmlAttribute* Find( const std::string& _name ) {
  752. return const_cast< TiXmlAttribute* >( const_cast< const TiXmlAttributeSet* >(this)->Find( _name ) );
  753. }
  754. #endif
  755. private:
  756. //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element),
  757. //*ME: this class must be also use a hidden/disabled copy-constructor !!!
  758. TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed
  759. void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute)
  760. TiXmlAttribute sentinel;
  761. };
  762. /** The element is a container class. It has a value, the element name,
  763. and can contain other elements, text, comments, and unknowns.
  764. Elements also contain an arbitrary number of attributes.
  765. */
  766. class TiXmlElement : public TiXmlNode
  767. {
  768. public:
  769. /// Construct an element.
  770. TiXmlElement (const char * in_value);
  771. #ifdef TIXML_USE_STL
  772. /// std::string constructor.
  773. TiXmlElement( const std::string& _value );
  774. #endif
  775. TiXmlElement( const TiXmlElement& );
  776. void operator=( const TiXmlElement& base );
  777. virtual ~TiXmlElement();
  778. /** Given an attribute name, Attribute() returns the value
  779. for the attribute of that name, or null if none exists.
  780. */
  781. const char* Attribute( const char* name ) const;
  782. /** Given an attribute name, Attribute() returns the value
  783. for the attribute of that name, or null if none exists.
  784. If the attribute exists and can be converted to an integer,
  785. the integer value will be put in the return 'i', if 'i'
  786. is non-null.
  787. */
  788. const char* Attribute( const char* name, int* i ) const;
  789. /** Given an attribute name, Attribute() returns the value
  790. for the attribute of that name, or null if none exists.
  791. If the attribute exists and can be converted to an double,
  792. the double value will be put in the return 'd', if 'd'
  793. is non-null.
  794. */
  795. const char* Attribute( const char* name, double* d ) const;
  796. /** QueryIntAttribute examines the attribute - it is an alternative to the
  797. Attribute() method with richer error checking.
  798. If the attribute is an integer, it is stored in 'value' and
  799. the call returns TIXML_SUCCESS. If it is not
  800. an integer, it returns TIXML_WRONG_TYPE. If the attribute
  801. does not exist, then TIXML_NO_ATTRIBUTE is returned.
  802. */
  803. int QueryIntAttribute( const char* name, int* _value ) const;
  804. /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute().
  805. int QueryDoubleAttribute( const char* name, double* _value ) const;
  806. /// QueryFloatAttribute examines the attribute - see QueryIntAttribute().
  807. int QueryFloatAttribute( const char* name, float* _value ) const {
  808. double d;
  809. int result = QueryDoubleAttribute( name, &d );
  810. if ( result == TIXML_SUCCESS ) {
  811. *_value = (float)d;
  812. }
  813. return result;
  814. }
  815. #ifdef TIXML_USE_STL
  816. /** Template form of the attribute query which will try to read the
  817. attribute into the specified type. Very easy, very powerful, but
  818. be careful to make sure to call this with the correct type.
  819. @return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE
  820. */
  821. template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const
  822. {
  823. const TiXmlAttribute* node = attributeSet.Find( name );
  824. if ( !node )
  825. return TIXML_NO_ATTRIBUTE;
  826. std::stringstream sstream( node->ValueStr() );
  827. sstream >> *outValue;
  828. if ( !sstream.fail() )
  829. return TIXML_SUCCESS;
  830. return TIXML_WRONG_TYPE;
  831. }
  832. #endif
  833. /** Sets an attribute of name to a given value. The attribute
  834. will be created if it does not exist, or changed if it does.
  835. */
  836. void SetAttribute( const char* name, const char * _value );
  837. #ifdef TIXML_USE_STL
  838. const std::string* Attribute( const std::string& name ) const;
  839. const std::string* Attribute( const std::string& name, int* i ) const;
  840. const std::string* Attribute( const std::string& name, double* d ) const;
  841. int QueryIntAttribute( const std::string& name, int* _value ) const;
  842. int QueryDoubleAttribute( const std::string& name, double* _value ) const;
  843. /// STL std::string form.
  844. void SetAttribute( const std::string& name, const std::string& _value );
  845. ///< STL std::string form.
  846. void SetAttribute( const std::string& name, int _value );
  847. #endif
  848. /** Sets an attribute of name to a given value. The attribute
  849. will be created if it does not exist, or changed if it does.
  850. */
  851. void SetAttribute( const char * name, int value );
  852. /** Sets an attribute of name to a given value. The attribute
  853. will be created if it does not exist, or changed if it does.
  854. */
  855. void SetDoubleAttribute( const char * name, double value );
  856. /** Deletes an attribute with the given name.
  857. */
  858. void RemoveAttribute( const char * name );
  859. #ifdef TIXML_USE_STL
  860. void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form.
  861. #endif
  862. const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element.
  863. TiXmlAttribute* FirstAttribute() { return attributeSet.First(); }
  864. const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element.
  865. TiXmlAttribute* LastAttribute() { return attributeSet.Last(); }
  866. /** Convenience function for easy access to the text inside an element. Although easy
  867. and concise, GetText() is limited compared to getting the TiXmlText child
  868. and accessing it directly.
  869. If the first child of 'this' is a TiXmlText, the GetText()
  870. returns the character string of the Text node, else null is returned.
  871. This is a convenient method for getting the text of simple contained text:
  872. @verbatim
  873. <foo>This is text</foo>
  874. const char* str = fooElement->GetText();
  875. @endverbatim
  876. 'str' will be a pointer to "This is text".
  877. Note that this function can be misleading. If the element foo was created from
  878. this XML:
  879. @verbatim
  880. <foo><b>This is text</b></foo>
  881. @endverbatim
  882. then the value of str would be null. The first child node isn't a text node, it is
  883. another element. From this XML:
  884. @verbatim
  885. <foo>This is <b>text</b></foo>
  886. @endverbatim
  887. GetText() will return "This is ".
  888. WARNING: GetText() accesses a child node - don't become confused with the
  889. similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are
  890. safe type casts on the referenced node.
  891. */
  892. const char* GetText() const;
  893. /// Creates a new Element and returns it - the returned element is a copy.
  894. virtual TiXmlNode* Clone() const;
  895. // Print the Element to a FILE stream.
  896. virtual void Print( FILE* cfile, int depth ) const;
  897. /* Attribtue parsing starts: next char past '<'
  898. returns: next char past '>'
  899. */
  900. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  901. virtual const TiXmlElement* ToElement() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  902. virtual TiXmlElement* ToElement() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  903. /** Walk the XML tree visiting this node and all of its children.
  904. */
  905. virtual bool Accept( TiXmlVisitor* visitor ) const;
  906. protected:
  907. void CopyTo( TiXmlElement* target ) const;
  908. void ClearThis(); // like clear, but initializes 'this' object as well
  909. // Used to be public [internal use]
  910. #ifdef TIXML_USE_STL
  911. virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
  912. #endif
  913. /* [internal use]
  914. Reads the "value" of the element -- another element, or text.
  915. This should terminate with the current end tag.
  916. */
  917. const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding );
  918. private:
  919. TiXmlAttributeSet attributeSet;
  920. };
  921. /** An XML comment.
  922. */
  923. class TiXmlComment : public TiXmlNode
  924. {
  925. public:
  926. /// Constructs an empty comment.
  927. TiXmlComment() : TiXmlNode( TiXmlNode::COMMENT ) {}
  928. /// Construct a comment from text.
  929. TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::COMMENT ) {
  930. SetValue( _value );
  931. }
  932. TiXmlComment( const TiXmlComment& );
  933. void operator=( const TiXmlComment& base );
  934. virtual ~TiXmlComment() {}
  935. /// Returns a copy of this Comment.
  936. virtual TiXmlNode* Clone() const;
  937. // Write this Comment to a FILE stream.
  938. virtual void Print( FILE* cfile, int depth ) const;
  939. /* Attribtue parsing starts: at the ! of the !--
  940. returns: next char past '>'
  941. */
  942. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  943. virtual const TiXmlComment* ToComment() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  944. virtual TiXmlComment* ToComment() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  945. /** Walk the XML tree visiting this node and all of its children.
  946. */
  947. virtual bool Accept( TiXmlVisitor* visitor ) const;
  948. protected:
  949. void CopyTo( TiXmlComment* target ) const;
  950. // used to be public
  951. #ifdef TIXML_USE_STL
  952. virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
  953. #endif
  954. // virtual void StreamOut( TIXML_OSTREAM * out ) const;
  955. private:
  956. };
  957. /** XML text. A text node can have 2 ways to output the next. "normal" output
  958. and CDATA. It will default to the mode it was parsed from the XML file and
  959. you generally want to leave it alone, but you can change the output mode with
  960. SetCDATA() and query it with CDATA().
  961. */
  962. class TiXmlText : public TiXmlNode
  963. {
  964. friend class TiXmlElement;
  965. public:
  966. /** Constructor for text element. By default, it is treated as
  967. normal, encoded text. If you want it be output as a CDATA text
  968. element, set the parameter _cdata to 'true'
  969. */
  970. TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TEXT)
  971. {
  972. SetValue( initValue );
  973. cdata = false;
  974. }
  975. virtual ~TiXmlText() {}
  976. #ifdef TIXML_USE_STL
  977. /// Constructor.
  978. TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TEXT)
  979. {
  980. SetValue( initValue );
  981. cdata = false;
  982. }
  983. #endif
  984. TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TEXT ) { copy.CopyTo( this ); }
  985. void operator=( const TiXmlText& base ) { base.CopyTo( this ); }
  986. // Write this text object to a FILE stream.
  987. virtual void Print( FILE* cfile, int depth ) const;
  988. /// Queries whether this represents text using a CDATA section.
  989. bool CDATA() const { return cdata; }
  990. /// Turns on or off a CDATA representation of text.
  991. void SetCDATA( bool _cdata ) { cdata = _cdata; }
  992. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  993. virtual const TiXmlText* ToText() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  994. virtual TiXmlText* ToText() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  995. /** Walk the XML tree visiting this node and all of its children.
  996. */
  997. virtual bool Accept( TiXmlVisitor* content ) const;
  998. protected :
  999. /// [internal use] Creates a new Element and returns it.
  1000. virtual TiXmlNode* Clone() const;
  1001. void CopyTo( TiXmlText* target ) const;
  1002. bool Blank() const; // returns true if all white space and new lines
  1003. // [internal use]
  1004. #ifdef TIXML_USE_STL
  1005. virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
  1006. #endif
  1007. private:
  1008. bool cdata; // true if this should be input and output as a CDATA style text element
  1009. };
  1010. /** In correct XML the declaration is the first entry in the file.
  1011. @verbatim
  1012. <?xml version="1.0" standalone="yes"?>
  1013. @endverbatim
  1014. TinyXml will happily read or write files without a declaration,
  1015. however. There are 3 possible attributes to the declaration:
  1016. version, encoding, and standalone.
  1017. Note: In this version of the code, the attributes are
  1018. handled as special cases, not generic attributes, simply
  1019. because there can only be at most 3 and they are always the same.
  1020. */
  1021. class TiXmlDeclaration : public TiXmlNode
  1022. {
  1023. public:
  1024. /// Construct an empty declaration.
  1025. TiXmlDeclaration() : TiXmlNode( TiXmlNode::DECLARATION ) {}
  1026. #ifdef TIXML_USE_STL
  1027. /// Constructor.
  1028. TiXmlDeclaration( const std::string& _version,
  1029. const std::string& _encoding,
  1030. const std::string& _standalone );
  1031. #endif
  1032. /// Construct.
  1033. TiXmlDeclaration( const char* _version,
  1034. const char* _encoding,
  1035. const char* _standalone );
  1036. TiXmlDeclaration( const TiXmlDeclaration& copy );
  1037. void operator=( const TiXmlDeclaration& copy );
  1038. virtual ~TiXmlDeclaration() {}
  1039. /// Version. Will return an empty string if none was found.
  1040. const char *Version() const { return version.c_str (); }
  1041. /// Encoding. Will return an empty string if none was found.
  1042. const char *Encoding() const { return encoding.c_str (); }
  1043. /// Is this a standalone document?
  1044. const char *Standalone() const { return standalone.c_str (); }
  1045. /// Creates a copy of this Declaration and returns it.
  1046. virtual TiXmlNode* Clone() const;
  1047. // Print this declaration to a FILE stream.
  1048. virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const;
  1049. virtual void Print( FILE* cfile, int depth ) const {
  1050. Print( cfile, depth, 0 );
  1051. }
  1052. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  1053. virtual const TiXmlDeclaration* ToDeclaration() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  1054. virtual TiXmlDeclaration* ToDeclaration() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  1055. /** Walk the XML tree visiting this node and all of its children.
  1056. */
  1057. virtual bool Accept( TiXmlVisitor* visitor ) const;
  1058. protected:
  1059. void CopyTo( TiXmlDeclaration* target ) const;
  1060. // used to be public
  1061. #ifdef TIXML_USE_STL
  1062. virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
  1063. #endif
  1064. private:
  1065. TIXML_STRING version;
  1066. TIXML_STRING encoding;
  1067. TIXML_STRING standalone;
  1068. };
  1069. /** Any tag that tinyXml doesn't recognize is saved as an
  1070. unknown. It is a tag of text, but should not be modified.
  1071. It will be written back to the XML, unchanged, when the file
  1072. is saved.
  1073. DTD tags get thrown into TiXmlUnknowns.
  1074. */
  1075. class TiXmlUnknown : public TiXmlNode
  1076. {
  1077. public:
  1078. TiXmlUnknown() : TiXmlNode( TiXmlNode::UNKNOWN ) {}
  1079. virtual ~TiXmlUnknown() {}
  1080. TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::UNKNOWN ) { copy.CopyTo( this ); }
  1081. void operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); }
  1082. /// Creates a copy of this Unknown and returns it.
  1083. virtual TiXmlNode* Clone() const;
  1084. // Print this Unknown to a FILE stream.
  1085. virtual void Print( FILE* cfile, int depth ) const;
  1086. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  1087. virtual const TiXmlUnknown* ToUnknown() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  1088. virtual TiXmlUnknown* ToUnknown() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  1089. /** Walk the XML tree visiting this node and all of its children.
  1090. */
  1091. virtual bool Accept( TiXmlVisitor* content ) const;
  1092. protected:
  1093. void CopyTo( TiXmlUnknown* target ) const;
  1094. #ifdef TIXML_USE_STL
  1095. virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
  1096. #endif
  1097. private:
  1098. };
  1099. /** Always the top level node. A document binds together all the
  1100. XML pieces. It can be saved, loaded, and printed to the screen.
  1101. The 'value' of a document node is the xml file name.
  1102. */
  1103. class TiXmlDocument : public TiXmlNode
  1104. {
  1105. public:
  1106. /// Create an empty document, that has no name.
  1107. TiXmlDocument();
  1108. /// Create a document with a name. The name of the document is also the filename of the xml.
  1109. TiXmlDocument( const char * documentName );
  1110. #ifdef TIXML_USE_STL
  1111. /// Constructor.
  1112. TiXmlDocument( const std::string& documentName );
  1113. #endif
  1114. TiXmlDocument( const TiXmlDocument& copy );
  1115. void operator=( const TiXmlDocument& copy );
  1116. virtual ~TiXmlDocument() {}
  1117. /** Load a file using the current document value.
  1118. Returns true if successful. Will delete any existing
  1119. document data before loading.
  1120. */
  1121. bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
  1122. /// Save a file using the current document value. Returns true if successful.
  1123. bool SaveFile() const;
  1124. /// Load a file using the given filename. Returns true if successful.
  1125. bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
  1126. /// Save a file using the given filename. Returns true if successful.
  1127. bool SaveFile( const char * filename ) const;
  1128. /** Load a file using the given FILE*. Returns true if successful. Note that this method
  1129. doesn't stream - the entire object pointed at by the FILE*
  1130. will be interpreted as an XML file. TinyXML doesn't stream in XML from the current
  1131. file location. Streaming may be added in the future.
  1132. */
  1133. bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
  1134. /// Save a file using the given FILE*. Returns true if successful.
  1135. bool SaveFile( FILE* ) const;
  1136. #ifdef TIXML_USE_STL
  1137. bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version.
  1138. {
  1139. // StringToBuffer f( filename );
  1140. // return ( f.buffer && LoadFile( f.buffer, encoding ));
  1141. return LoadFile( filename.c_str(), encoding );
  1142. }
  1143. bool SaveFile( const std::string& filename ) const ///< STL std::string version.
  1144. {
  1145. // StringToBuffer f( filename );
  1146. // return ( f.buffer && SaveFile( f.buffer ));
  1147. return SaveFile( filename.c_str() );
  1148. }
  1149. #endif
  1150. /** Parse the given null terminated block of xml data. Passing in an encoding to this
  1151. method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml
  1152. to use that encoding, regardless of what TinyXml might otherwise try to detect.
  1153. */
  1154. virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
  1155. /** Get the root element -- the only top level element -- of the document.
  1156. In well formed XML, there should only be one. TinyXml is tolerant of
  1157. multiple elements at the document level.
  1158. */
  1159. const TiXmlElement* RootElement() const { return FirstChildElement(); }
  1160. TiXmlElement* RootElement() { return FirstChildElement(); }
  1161. /** If an error occurs, Error will be set to true. Also,
  1162. - The ErrorId() will contain the integer identifier of the error (not generally useful)
  1163. - The ErrorDesc() method will return the name of the error. (very useful)
  1164. - The ErrorRow() and ErrorCol() will return the location of the error (if known)
  1165. */
  1166. bool Error() const { return error; }
  1167. /// Contains a textual (english) description of the error if one occurs.
  1168. const char * ErrorDesc() const { return errorDesc.c_str (); }
  1169. /** Generally, you probably want the error string ( ErrorDesc() ). But if you
  1170. prefer the ErrorId, this function will fetch it.
  1171. */
  1172. int ErrorId() const { return errorId; }
  1173. /** Returns the location (if known) of the error. The first column is column 1,
  1174. and the first row is row 1. A value of 0 means the row and column wasn't applicable
  1175. (memory errors, for example, have no row/column) or the parser lost the error. (An
  1176. error in the error reporting, in that case.)
  1177. @sa SetTabSize, Row, Column
  1178. */
  1179. int ErrorRow() { return errorLocation.row+1; }
  1180. int ErrorCol() { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow()
  1181. /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol())
  1182. to report the correct values for row and column. It does not change the output
  1183. or input in any way.
  1184. By calling this method, with a tab size
  1185. greater than 0, the row and column of each node and attribute is stored
  1186. when the file is loaded. Very useful for tracking the DOM back in to
  1187. the source file.
  1188. The tab size is required for calculating the location of nodes. If not
  1189. set, the default of 4 is used. The tabsize is set per document. Setting
  1190. the tabsize to 0 disables row/column tracking.
  1191. Note that row and column tracking is not supported when using operator>>.
  1192. The tab size needs to be enabled before the parse or load. Correct usage:
  1193. @verbatim
  1194. TiXmlDocument doc;
  1195. doc.SetTabSize( 8 );
  1196. doc.Load( "myfile.xml" );
  1197. @endverbatim
  1198. @sa Row, Column
  1199. */
  1200. void SetTabSize( int _tabsize ) { tabsize = _tabsize; }
  1201. int TabSize() const { return tabsize; }
  1202. /** If you have handled the error, it can be reset with this call. The error
  1203. state is automatically cleared if you Parse a new XML block.
  1204. */
  1205. void ClearError() { error = false;
  1206. errorId = 0;
  1207. errorDesc = "";
  1208. errorLocation.row = errorLocation.col = 0;
  1209. //errorLocation.last = 0;
  1210. }
  1211. /** Write the document to standard out using formatted printing ("pretty print"). */
  1212. void Print() const { Print( stdout, 0 ); }
  1213. /* Write the document to a string using formatted printing ("pretty print"). This
  1214. will allocate a character array (new char[]) and return it as a pointer. The
  1215. calling code pust call delete[] on the return char* to avoid a memory leak.
  1216. */
  1217. //char* PrintToMemory() const;
  1218. /// Print this Document to a FILE stream.
  1219. virtual void Print( FILE* cfile, int depth = 0 ) const;
  1220. // [internal use]
  1221. void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding );
  1222. virtual const TiXmlDocument* ToDocument() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  1223. virtual TiXmlDocument* ToDocument() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
  1224. /** Walk the XML tree visiting this node and all of its children.
  1225. */
  1226. virtual bool Accept( TiXmlVisitor* content ) const;
  1227. protected :
  1228. // [internal use]
  1229. virtual TiXmlNode* Clone() const;
  1230. #ifdef TIXML_USE_STL
  1231. virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
  1232. #endif
  1233. private:
  1234. void CopyTo( TiXmlDocument* target ) const;
  1235. bool error;
  1236. int errorId;
  1237. TIXML_STRING errorDesc;
  1238. int tabsize;
  1239. TiXmlCursor errorLocation;
  1240. bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write.
  1241. };
  1242. /**
  1243. A TiXmlHandle is a class that wraps a node pointer with null checks; this is
  1244. an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml
  1245. DOM structure. It is a separate utility class.
  1246. Take an example:
  1247. @verbatim
  1248. <Document>
  1249. <Element attributeA = "valueA">
  1250. <Child attributeB = "value1" />
  1251. <Child attributeB = "value2" />
  1252. </Element>
  1253. <Document>
  1254. @endverbatim
  1255. Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
  1256. easy to write a *lot* of code that looks like:
  1257. @verbatim
  1258. TiXmlElement* root = document.FirstChildElement( "Document" );
  1259. if ( root )
  1260. {
  1261. TiXmlElement* element = root->FirstChildElement( "Element" );
  1262. if ( element )
  1263. {
  1264. TiXmlElement* child = element->FirstChildElement( "Child" );
  1265. if ( child )
  1266. {
  1267. TiXmlElement* child2 = child->NextSiblingElement( "Child" );
  1268. if ( child2 )
  1269. {
  1270. // Finally do something useful.
  1271. @endverbatim
  1272. And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity
  1273. of such code. A TiXmlHandle checks for null pointers so it is perfectly safe
  1274. and correct to use:
  1275. @verbatim
  1276. TiXmlHandle docHandle( &document );
  1277. TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).ToElement();
  1278. if ( child2 )
  1279. {
  1280. // do something useful
  1281. @endverbatim
  1282. Which is MUCH more concise and useful.
  1283. It is also safe to copy handles - internally they are nothing more than node pointers.
  1284. @verbatim
  1285. TiXmlHandle handleCopy = handle;
  1286. @endverbatim
  1287. What they should not be used for is iteration:
  1288. @verbatim
  1289. int i=0;
  1290. while ( true )
  1291. {
  1292. TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).ToElement();
  1293. if ( !child )
  1294. break;
  1295. // do something
  1296. ++i;
  1297. }
  1298. @endverbatim
  1299. It seems reasonable, but it is in fact two embedded while loops. The Child method is
  1300. a linear walk to find the element, so this code would iterate much more than it needs
  1301. to. Instead, prefer:
  1302. @verbatim
  1303. TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).ToElement();
  1304. for( child; child; child=child->NextSiblingElement() )
  1305. {
  1306. // do something
  1307. }
  1308. @endverbatim
  1309. */
  1310. class TiXmlHandle
  1311. {
  1312. public:
  1313. /// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
  1314. TiXmlHandle( TiXmlNode* _node ) { this->node = _node; }
  1315. /// Copy constructor
  1316. TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; }
  1317. TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; }
  1318. /// Return a handle to the first child node.
  1319. TiXmlHandle FirstChild() const;
  1320. /// Return a handle to the first child node with the given name.
  1321. TiXmlHandle FirstChild( const char * value ) const;
  1322. /// Return a handle to the first child element.
  1323. TiXmlHandle FirstChildElement() const;
  1324. /// Return a handle to the first child element with the given name.
  1325. TiXmlHandle FirstChildElement( const char * value ) const;
  1326. /** Return a handle to the "index" child with the given name.
  1327. The first child is 0, the second 1, etc.
  1328. */
  1329. TiXmlHandle Child( const char* value, int index ) const;
  1330. /** Return a handle to the "index" child.
  1331. The first child is 0, the second 1, etc.
  1332. */
  1333. TiXmlHandle Child( int index ) const;
  1334. /** Return a handle to the "index" child element with the given name.
  1335. The first child element is 0, the second 1, etc. Note that only TiXmlElements
  1336. are indexed: other types are not counted.
  1337. */
  1338. TiXmlHandle ChildElement( const char* value, int index ) const;
  1339. /** Return a handle to the "index" child element.
  1340. The first child element is 0, the second 1, etc. Note that only TiXmlElements
  1341. are indexed: other types are not counted.
  1342. */
  1343. TiXmlHandle ChildElement( int index ) const;
  1344. #ifdef TIXML_USE_STL
  1345. TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); }
  1346. TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); }
  1347. TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); }
  1348. TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); }
  1349. #endif
  1350. /** Return the handle as a TiXmlNode. This may return null.
  1351. */
  1352. TiXmlNode* ToNode() const { return node; }
  1353. /** Return the handle as a TiXmlElement. This may return null.
  1354. */
  1355. TiXmlElement* ToElement() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); }
  1356. /** Return the handle as a TiXmlText. This may return null.
  1357. */
  1358. TiXmlText* ToText() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); }
  1359. /** Return the handle as a TiXmlUnknown. This may return null.
  1360. */
  1361. TiXmlUnknown* ToUnknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); }
  1362. /** @deprecated use ToNode.
  1363. Return the handle as a TiXmlNode. This may return null.
  1364. */
  1365. TiXmlNode* Node() const { return ToNode(); }
  1366. /** @deprecated use ToElement.
  1367. Return the handle as a TiXmlElement. This may return null.
  1368. */
  1369. TiXmlElement* Element() const { return ToElement(); }
  1370. /** @deprecated use ToText()
  1371. Return the handle as a TiXmlText. This may return null.
  1372. */
  1373. TiXmlText* Text() const { return ToText(); }
  1374. /** @deprecated use ToUnknown()
  1375. Return the handle as a TiXmlUnknown. This may return null.
  1376. */
  1377. TiXmlUnknown* Unknown() const { return ToUnknown(); }
  1378. private:
  1379. TiXmlNode* node;
  1380. };
  1381. /** Print to memory functionality. The TiXmlPrinter is useful when you need to:
  1382. -# Print to memory (especially in non-STL mode)
  1383. -# Control formatting (line endings, etc.)
  1384. When constructed, the TiXmlPrinter is in its default "pretty printing" mode.
  1385. Before calling Accept() you can call methods to control the printing
  1386. of the XML document. After TiXmlNode::Accept() is called, the printed document can
  1387. be accessed via the CStr(), Str(), and Size() methods.
  1388. TiXmlPrinter uses the Visitor API.
  1389. @verbatim
  1390. TiXmlPrinter printer;
  1391. printer.SetIndent( "\t" );
  1392. doc.Accept( &printer );
  1393. fprintf( stdout, "%s", printer.CStr() );
  1394. @endverbatim
  1395. */
  1396. class TiXmlPrinter : public TiXmlVisitor
  1397. {
  1398. public:
  1399. TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ),
  1400. buffer(), indent( " " ), lineBreak( "\n" ) {}
  1401. virtual bool VisitEnter( const TiXmlDocument& doc );
  1402. virtual bool VisitExit( const TiXmlDocument& doc );
  1403. virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute );
  1404. virtual bool VisitExit( const TiXmlElement& element );
  1405. virtual bool Visit( const TiXmlDeclaration& declaration );
  1406. virtual bool Visit( const TiXmlText& text );
  1407. virtual bool Visit( const TiXmlComment& comment );
  1408. virtual bool Visit( const TiXmlUnknown& unknown );
  1409. /** Set the indent characters for printing. By default 4 spaces
  1410. but tab (\t) is also useful, or null/empty string for no indentation.
  1411. */
  1412. void SetIndent( const char* _indent ) { indent = _indent ? _indent : "" ; }
  1413. /// Query the indention string.
  1414. const char* Indent() { return indent.c_str(); }
  1415. /** Set the line breaking string. By default set to newline (\n).
  1416. Some operating systems prefer other characters, or can be
  1417. set to the null/empty string for no indenation.
  1418. */
  1419. void SetLineBreak( const char* _lineBreak ) { lineBreak = _lineBreak ? _lineBreak : ""; }
  1420. /// Query the current line breaking string.
  1421. const char* LineBreak() { return lineBreak.c_str(); }
  1422. /** Switch over to "stream printing" which is the most dense formatting without
  1423. linebreaks. Common when the XML is needed for network transmission.
  1424. */
  1425. void SetStreamPrinting() { indent = "";
  1426. lineBreak = "";
  1427. }
  1428. /// Return the result.
  1429. const char* CStr() { return buffer.c_str(); }
  1430. /// Return the length of the result string.
  1431. size_t Size() { return buffer.size(); }
  1432. #ifdef TIXML_USE_STL
  1433. /// Return the result.
  1434. const std::string& Str() { return buffer; }
  1435. #endif
  1436. private:
  1437. void DoIndent() {
  1438. for( int i=0; i<depth; ++i )
  1439. buffer += indent;
  1440. }
  1441. void DoLineBreak() {
  1442. buffer += lineBreak;
  1443. }
  1444. int depth;
  1445. bool simpleTextPrint;
  1446. TIXML_STRING buffer;
  1447. TIXML_STRING indent;
  1448. TIXML_STRING lineBreak;
  1449. };
  1450. #ifdef _MSC_VER
  1451. #pragma warning( pop )
  1452. #endif
  1453. #endif