tinyxml.h 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  1. /*
  2. www.sourceforge.net/projects/tinyxml
  3. Original code (2.0 and earlier )copyright (c) 2000-2002 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( disable : 4530 )
  23. #pragma warning( disable : 4786 )
  24. #endif
  25. #include <ctype.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <assert.h>
  30. // Help out windows:
  31. #if defined( _DEBUG ) && !defined( DEBUG )
  32. #define DEBUG
  33. #endif
  34. #if defined( DEBUG ) && defined( _MSC_VER )
  35. #include <windows.h>
  36. #define TIXML_LOG OutputDebugString
  37. #else
  38. #define TIXML_LOG printf
  39. #endif
  40. #ifdef TIXML_USE_STL
  41. #include <string>
  42. #include <iostream>
  43. #define TIXML_STRING std::string
  44. #define TIXML_ISTREAM std::istream
  45. #define TIXML_OSTREAM std::ostream
  46. #else
  47. #include "tinystr.h"
  48. #define TIXML_STRING TiXmlString
  49. #define TIXML_OSTREAM TiXmlOutStream
  50. #endif
  51. class TiXmlDocument;
  52. class TiXmlElement;
  53. class TiXmlComment;
  54. class TiXmlUnknown;
  55. class TiXmlAttribute;
  56. class TiXmlText;
  57. class TiXmlDeclaration;
  58. class TiXmlParsingData;
  59. const int TIXML_MAJOR_VERSION = 2;
  60. const int TIXML_MINOR_VERSION = 3;
  61. const int TIXML_PATCH_VERSION = 4;
  62. /* Internal structure for tracking location of items
  63. in the XML file.
  64. */
  65. struct TiXmlCursor
  66. {
  67. TiXmlCursor() { Clear(); }
  68. void Clear() { row = col = -1; }
  69. int row; // 0 based.
  70. int col; // 0 based.
  71. };
  72. // Only used by Attribute::Query functions
  73. enum
  74. {
  75. TIXML_SUCCESS,
  76. TIXML_NO_ATTRIBUTE,
  77. TIXML_WRONG_TYPE
  78. };
  79. // Used by the parsing routines.
  80. enum TiXmlEncoding
  81. {
  82. TIXML_ENCODING_UNKNOWN,
  83. TIXML_ENCODING_UTF8,
  84. TIXML_ENCODING_LEGACY
  85. };
  86. const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN;
  87. /** TiXmlBase is a base class for every class in TinyXml.
  88. It does little except to establish that TinyXml classes
  89. can be printed and provide some utility functions.
  90. In XML, the document and elements can contain
  91. other elements and other types of nodes.
  92. @verbatim
  93. A Document can contain: Element (container or leaf)
  94. Comment (leaf)
  95. Unknown (leaf)
  96. Declaration( leaf )
  97. An Element can contain: Element (container or leaf)
  98. Text (leaf)
  99. Attributes (not on tree)
  100. Comment (leaf)
  101. Unknown (leaf)
  102. A Decleration contains: Attributes (not on tree)
  103. @endverbatim
  104. */
  105. class TiXmlBase
  106. {
  107. friend class TiXmlNode;
  108. friend class TiXmlElement;
  109. friend class TiXmlDocument;
  110. public:
  111. TiXmlBase() : userData(0) {}
  112. virtual ~TiXmlBase() {}
  113. /** All TinyXml classes can print themselves to a filestream.
  114. This is a formatted print, and will insert tabs and newlines.
  115. (For an unformatted stream, use the << operator.)
  116. */
  117. virtual void Print( FILE* cfile, int depth ) const = 0;
  118. /** The world does not agree on whether white space should be kept or
  119. not. In order to make everyone happy, these global, static functions
  120. are provided to set whether or not TinyXml will condense all white space
  121. into a single space or not. The default is to condense. Note changing this
  122. values is not thread safe.
  123. */
  124. static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; }
  125. /// Return the current white space setting.
  126. static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; }
  127. /** Return the position, in the original source file, of this node or attribute.
  128. The row and column are 1-based. (That is the first row and first column is
  129. 1,1). If the returns values are 0 or less, then the parser does not have
  130. a row and column value.
  131. Generally, the row and column value will be set when the TiXmlDocument::Load(),
  132. TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set
  133. when the DOM was created from operator>>.
  134. The values reflect the initial load. Once the DOM is modified programmatically
  135. (by adding or changing nodes and attributes) the new values will NOT update to
  136. reflect changes in the document.
  137. There is a minor performance cost to computing the row and column. Computation
  138. can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value.
  139. @sa TiXmlDocument::SetTabSize()
  140. */
  141. int Row() const { return location.row + 1; }
  142. int Column() const { return location.col + 1; } ///< See Row()
  143. void SetUserData( void* user ) { userData = user; }
  144. void* GetUserData() { return userData; }
  145. // Table that returs, for a given lead byte, the total number of bytes
  146. // in the UTF-8 sequence.
  147. static const int utf8ByteTable[256];
  148. virtual const char* Parse( const char* p,
  149. TiXmlParsingData* data,
  150. TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0;
  151. enum
  152. {
  153. TIXML_NO_ERROR = 0,
  154. TIXML_ERROR,
  155. TIXML_ERROR_OPENING_FILE,
  156. TIXML_ERROR_OUT_OF_MEMORY,
  157. TIXML_ERROR_PARSING_ELEMENT,
  158. TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME,
  159. TIXML_ERROR_READING_ELEMENT_VALUE,
  160. TIXML_ERROR_READING_ATTRIBUTES,
  161. TIXML_ERROR_PARSING_EMPTY,
  162. TIXML_ERROR_READING_END_TAG,
  163. TIXML_ERROR_PARSING_UNKNOWN,
  164. TIXML_ERROR_PARSING_COMMENT,
  165. TIXML_ERROR_PARSING_DECLARATION,
  166. TIXML_ERROR_DOCUMENT_EMPTY,
  167. TIXML_ERROR_EMBEDDED_NULL,
  168. TIXML_ERROR_STRING_COUNT
  169. };
  170. protected:
  171. // See STL_STRING_BUG
  172. // Utility class to overcome a bug.
  173. class StringToBuffer
  174. {
  175. public:
  176. StringToBuffer( const TIXML_STRING& str );
  177. ~StringToBuffer();
  178. char* buffer;
  179. };
  180. static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding );
  181. inline static bool IsWhiteSpace( char c )
  182. {
  183. return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' );
  184. }
  185. virtual void StreamOut (TIXML_OSTREAM *) const = 0;
  186. #ifdef TIXML_USE_STL
  187. static bool StreamWhiteSpace( TIXML_ISTREAM * in, TIXML_STRING * tag );
  188. static bool StreamTo( TIXML_ISTREAM * in, int character, TIXML_STRING * tag );
  189. #endif
  190. /* Reads an XML name into the string provided. Returns
  191. a pointer just past the last character of the name,
  192. or 0 if the function has an error.
  193. */
  194. static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding );
  195. /* Reads text. Returns a pointer past the given end tag.
  196. Wickedly complex options, but it keeps the (sensitive) code in one place.
  197. */
  198. static const char* ReadText( const char* in, // where to start
  199. TIXML_STRING* text, // the string read
  200. bool ignoreWhiteSpace, // whether to keep the white space
  201. const char* endTag, // what ends this text
  202. bool ignoreCase, // whether to ignore case in the end tag
  203. TiXmlEncoding encoding ); // the current encoding
  204. // If an entity has been found, transform it into a character.
  205. static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding );
  206. // Get a character, while interpreting entities.
  207. // The length can be from 0 to 4 bytes.
  208. inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding )
  209. {
  210. assert( p );
  211. if ( encoding == TIXML_ENCODING_UTF8 )
  212. {
  213. *length = utf8ByteTable[ *((unsigned char*)p) ];
  214. assert( *length >= 0 && *length < 5 );
  215. }
  216. else
  217. {
  218. *length = 1;
  219. }
  220. if ( *length == 1 )
  221. {
  222. if ( *p == '&' )
  223. return GetEntity( p, _value, length, encoding );
  224. *_value = *p;
  225. return p+1;
  226. }
  227. else if ( *length )
  228. {
  229. strncpy( _value, p, *length );
  230. return p + (*length);
  231. }
  232. else
  233. {
  234. // Not valid text.
  235. return 0;
  236. }
  237. }
  238. // Puts a string to a stream, expanding entities as it goes.
  239. // Note this should not contian the '<', '>', etc, or they will be transformed into entities!
  240. static void PutString( const TIXML_STRING& str, TIXML_OSTREAM* out );
  241. static void PutString( const TIXML_STRING& str, TIXML_STRING* out );
  242. // Return true if the next characters in the stream are any of the endTag sequences.
  243. // Ignore case only works for english, and should only be relied on when comparing
  244. // to Engilish words: StringEqual( p, "version", true ) is fine.
  245. static bool StringEqual( const char* p,
  246. const char* endTag,
  247. bool ignoreCase,
  248. TiXmlEncoding encoding );
  249. static const char* errorString[ TIXML_ERROR_STRING_COUNT ];
  250. TiXmlCursor location;
  251. /// Field containing a generic user pointer
  252. void* userData;
  253. // None of these methods are reliable for any language except English.
  254. // Good for approximation, not great for accuracy.
  255. static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding );
  256. static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding );
  257. inline static int ToLower( int v, TiXmlEncoding encoding )
  258. {
  259. if ( encoding == TIXML_ENCODING_UTF8 )
  260. {
  261. if ( v < 128 ) return tolower( v );
  262. return v;
  263. }
  264. else
  265. {
  266. return tolower( v );
  267. }
  268. }
  269. static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
  270. private:
  271. TiXmlBase( const TiXmlBase& ); // not implemented.
  272. void operator=( const TiXmlBase& base ); // not allowed.
  273. struct Entity
  274. {
  275. const char* str;
  276. unsigned int strLength;
  277. char chr;
  278. };
  279. enum
  280. {
  281. NUM_ENTITY = 5,
  282. MAX_ENTITY_LENGTH = 6
  283. };
  284. static Entity entity[ NUM_ENTITY ];
  285. static bool condenseWhiteSpace;
  286. };
  287. /** The parent class for everything in the Document Object Model.
  288. (Except for attributes).
  289. Nodes have siblings, a parent, and children. A node can be
  290. in a document, or stand on its own. The type of a TiXmlNode
  291. can be queried, and it can be cast to its more defined type.
  292. */
  293. class TiXmlNode : public TiXmlBase
  294. {
  295. friend class TiXmlDocument;
  296. friend class TiXmlElement;
  297. public:
  298. #ifdef TIXML_USE_STL
  299. /** An input stream operator, for every class. Tolerant of newlines and
  300. formatting, but doesn't expect them.
  301. */
  302. friend std::istream& operator >> (std::istream& in, TiXmlNode& base);
  303. /** An output stream operator, for every class. Note that this outputs
  304. without any newlines or formatting, as opposed to Print(), which
  305. includes tabs and new lines.
  306. The operator<< and operator>> are not completely symmetric. Writing
  307. a node to a stream is very well defined. You'll get a nice stream
  308. of output, without any extra whitespace or newlines.
  309. But reading is not as well defined. (As it always is.) If you create
  310. a TiXmlElement (for example) and read that from an input stream,
  311. the text needs to define an element or junk will result. This is
  312. true of all input streams, but it's worth keeping in mind.
  313. A TiXmlDocument will read nodes until it reads a root element, and
  314. all the children of that root element.
  315. */
  316. friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base);
  317. /// Appends the XML node or attribute to a std::string.
  318. friend std::string& operator<< (std::string& out, const TiXmlNode& base );
  319. #else
  320. // Used internally, not part of the public API.
  321. friend TIXML_OSTREAM& operator<< (TIXML_OSTREAM& out, const TiXmlNode& base);
  322. #endif
  323. /** The types of XML nodes supported by TinyXml. (All the
  324. unsupported types are picked up by UNKNOWN.)
  325. */
  326. enum NodeType
  327. {
  328. DOCUMENT,
  329. ELEMENT,
  330. COMMENT,
  331. UNKNOWN,
  332. TEXT,
  333. DECLARATION,
  334. TYPECOUNT
  335. };
  336. virtual ~TiXmlNode();
  337. /** The meaning of 'value' changes for the specific type of
  338. TiXmlNode.
  339. @verbatim
  340. Document: filename of the xml file
  341. Element: name of the element
  342. Comment: the comment text
  343. Unknown: the tag contents
  344. Text: the text string
  345. @endverbatim
  346. The subclasses will wrap this function.
  347. */
  348. const char * Value() const { return value.c_str (); }
  349. /** Changes the value of the node. Defined as:
  350. @verbatim
  351. Document: filename of the xml file
  352. Element: name of the element
  353. Comment: the comment text
  354. Unknown: the tag contents
  355. Text: the text string
  356. @endverbatim
  357. */
  358. void SetValue(const char * _value) { value = _value;}
  359. #ifdef TIXML_USE_STL
  360. /// STL std::string form.
  361. void SetValue( const std::string& _value )
  362. {
  363. StringToBuffer buf( _value );
  364. SetValue( buf.buffer ? buf.buffer : "" );
  365. }
  366. #endif
  367. /// Delete all the children of this node. Does not affect 'this'.
  368. void Clear();
  369. /// One step up the DOM.
  370. TiXmlNode* Parent() { return parent; }
  371. const TiXmlNode* Parent() const { return parent; }
  372. const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children.
  373. TiXmlNode* FirstChild() { return firstChild; }
  374. const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found.
  375. TiXmlNode* FirstChild( const char * value ); ///< The first child of this node with the matching 'value'. Will be null if none found.
  376. const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children.
  377. TiXmlNode* LastChild() { return lastChild; }
  378. const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children.
  379. TiXmlNode* LastChild( const char * value );
  380. #ifdef TIXML_USE_STL
  381. const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form.
  382. TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form.
  383. const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form.
  384. TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form.
  385. #endif
  386. /** An alternate way to walk the children of a node.
  387. One way to iterate over nodes is:
  388. @verbatim
  389. for( child = parent->FirstChild(); child; child = child->NextSibling() )
  390. @endverbatim
  391. IterateChildren does the same thing with the syntax:
  392. @verbatim
  393. child = 0;
  394. while( child = parent->IterateChildren( child ) )
  395. @endverbatim
  396. IterateChildren takes the previous child as input and finds
  397. the next one. If the previous child is null, it returns the
  398. first. IterateChildren will return null when done.
  399. */
  400. const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const;
  401. TiXmlNode* IterateChildren( TiXmlNode* previous );
  402. /// This flavor of IterateChildren searches for children with a particular 'value'
  403. const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const;
  404. TiXmlNode* IterateChildren( const char * value, TiXmlNode* previous );
  405. #ifdef TIXML_USE_STL
  406. const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
  407. TiXmlNode* IterateChildren( const std::string& _value, TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
  408. #endif
  409. /** Add a new node related to this. Adds a child past the LastChild.
  410. Returns a pointer to the new object or NULL if an error occured.
  411. */
  412. TiXmlNode* InsertEndChild( const TiXmlNode& addThis );
  413. /** Add a new node related to this. Adds a child past the LastChild.
  414. NOTE: the node to be added is passed by pointer, and will be
  415. henceforth owned (and deleted) by tinyXml. This method is efficient
  416. and avoids an extra copy, but should be used with care as it
  417. uses a different memory model than the other insert functions.
  418. @sa InsertEndChild
  419. */
  420. TiXmlNode* LinkEndChild( TiXmlNode* addThis );
  421. /** Add a new node related to this. Adds a child before the specified child.
  422. Returns a pointer to the new object or NULL if an error occured.
  423. */
  424. TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis );
  425. /** Add a new node related to this. Adds a child after the specified child.
  426. Returns a pointer to the new object or NULL if an error occured.
  427. */
  428. TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis );
  429. /** Replace a child of this node.
  430. Returns a pointer to the new object or NULL if an error occured.
  431. */
  432. TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis );
  433. /// Delete a child of this node.
  434. bool RemoveChild( TiXmlNode* removeThis );
  435. /// Navigate to a sibling node.
  436. const TiXmlNode* PreviousSibling() const { return prev; }
  437. TiXmlNode* PreviousSibling() { return prev; }
  438. /// Navigate to a sibling node.
  439. const TiXmlNode* PreviousSibling( const char * ) const;
  440. TiXmlNode* PreviousSibling( const char * );
  441. #ifdef TIXML_USE_STL
  442. const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
  443. TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
  444. const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form.
  445. TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form.
  446. #endif
  447. /// Navigate to a sibling node.
  448. const TiXmlNode* NextSibling() const { return next; }
  449. TiXmlNode* NextSibling() { return next; }
  450. /// Navigate to a sibling node with the given 'value'.
  451. const TiXmlNode* NextSibling( const char * ) const;
  452. TiXmlNode* NextSibling( const char * );
  453. /** Convenience function to get through elements.
  454. Calls NextSibling and ToElement. Will skip all non-Element
  455. nodes. Returns 0 if there is not another element.
  456. */
  457. const TiXmlElement* NextSiblingElement() const;
  458. TiXmlElement* NextSiblingElement();
  459. /** Convenience function to get through elements.
  460. Calls NextSibling and ToElement. Will skip all non-Element
  461. nodes. Returns 0 if there is not another element.
  462. */
  463. const TiXmlElement* NextSiblingElement( const char * ) const;
  464. TiXmlElement* NextSiblingElement( const char * );
  465. #ifdef TIXML_USE_STL
  466. const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
  467. TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
  468. #endif
  469. /// Convenience function to get through elements.
  470. const TiXmlElement* FirstChildElement() const;
  471. TiXmlElement* FirstChildElement();
  472. /// Convenience function to get through elements.
  473. const TiXmlElement* FirstChildElement( const char * value ) const;
  474. TiXmlElement* FirstChildElement( const char * value );
  475. #ifdef TIXML_USE_STL
  476. const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
  477. TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
  478. #endif
  479. /** Query the type (as an enumerated value, above) of this node.
  480. The possible types are: DOCUMENT, ELEMENT, COMMENT,
  481. UNKNOWN, TEXT, and DECLARATION.
  482. */
  483. virtual int Type() const { return type; }
  484. /** Return a pointer to the Document this node lives in.
  485. Returns null if not in a document.
  486. */
  487. const TiXmlDocument* GetDocument() const;
  488. TiXmlDocument* GetDocument();
  489. /// Returns true if this node has no children.
  490. bool NoChildren() const { return !firstChild; }
  491. const TiXmlDocument* ToDocument() const { return ( this && type == DOCUMENT ) ? (const TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  492. const TiXmlElement* ToElement() const { return ( this && type == ELEMENT ) ? (const TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  493. const TiXmlComment* ToComment() const { return ( this && type == COMMENT ) ? (const TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  494. const TiXmlUnknown* ToUnknown() const { return ( this && type == UNKNOWN ) ? (const TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  495. const TiXmlText* ToText() const { return ( this && type == TEXT ) ? (const TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  496. const TiXmlDeclaration* ToDeclaration() const { return ( this && type == DECLARATION ) ? (const TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  497. TiXmlDocument* ToDocument() { return ( this && type == DOCUMENT ) ? (TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  498. TiXmlElement* ToElement() { return ( this && type == ELEMENT ) ? (TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  499. TiXmlComment* ToComment() { return ( this && type == COMMENT ) ? (TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  500. TiXmlUnknown* ToUnknown() { return ( this && type == UNKNOWN ) ? (TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  501. TiXmlText* ToText() { return ( this && type == TEXT ) ? (TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  502. TiXmlDeclaration* ToDeclaration() { return ( this && type == DECLARATION ) ? (TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
  503. /** Create an exact duplicate of this node and return it. The memory must be deleted
  504. by the caller.
  505. */
  506. virtual TiXmlNode* Clone() const = 0;
  507. protected:
  508. TiXmlNode( NodeType _type );
  509. // Copy to the allocated object. Shared functionality between Clone, Copy constructor,
  510. // and the assignment operator.
  511. void CopyTo( TiXmlNode* target ) const;
  512. #ifdef TIXML_USE_STL
  513. // The real work of the input operator.
  514. virtual void StreamIn( TIXML_ISTREAM* in, TIXML_STRING* tag ) = 0;
  515. #endif
  516. // Figure out what is at *p, and parse it. Returns null if it is not an xml node.
  517. TiXmlNode* Identify( const char* start, TiXmlEncoding encoding );
  518. // Internal Value function returning a TIXML_STRING
  519. const TIXML_STRING& SValue() const { return value ; }
  520. TiXmlNode* parent;
  521. NodeType type;
  522. TiXmlNode* firstChild;
  523. TiXmlNode* lastChild;
  524. TIXML_STRING value;
  525. TiXmlNode* prev;
  526. TiXmlNode* next;
  527. private:
  528. TiXmlNode( const TiXmlNode& ); // not implemented.
  529. void operator=( const TiXmlNode& base ); // not allowed.
  530. };
  531. /** An attribute is a name-value pair. Elements have an arbitrary
  532. number of attributes, each with a unique name.
  533. @note The attributes are not TiXmlNodes, since they are not
  534. part of the tinyXML document object model. There are other
  535. suggested ways to look at this problem.
  536. */
  537. class TiXmlAttribute : public TiXmlBase
  538. {
  539. friend class TiXmlAttributeSet;
  540. public:
  541. /// Construct an empty attribute.
  542. TiXmlAttribute() : TiXmlBase()
  543. {
  544. document = 0;
  545. prev = next = 0;
  546. }
  547. #ifdef TIXML_USE_STL
  548. /// std::string constructor.
  549. TiXmlAttribute( const std::string& _name, const std::string& _value )
  550. {
  551. name = _name;
  552. value = _value;
  553. document = 0;
  554. prev = next = 0;
  555. }
  556. #endif
  557. /// Construct an attribute with a name and value.
  558. TiXmlAttribute( const char * _name, const char * _value )
  559. {
  560. name = _name;
  561. value = _value;
  562. document = 0;
  563. prev = next = 0;
  564. }
  565. const char* Name() const { return name.c_str (); } ///< Return the name of this attribute.
  566. const char* Value() const { return value.c_str (); } ///< Return the value of this attribute.
  567. const int IntValue() const; ///< Return the value of this attribute, converted to an integer.
  568. const double DoubleValue() const; ///< Return the value of this attribute, converted to a double.
  569. /** QueryIntValue examines the value string. It is an alternative to the
  570. IntValue() method with richer error checking.
  571. If the value is an integer, it is stored in 'value' and
  572. the call returns TIXML_SUCCESS. If it is not
  573. an integer, it returns TIXML_WRONG_TYPE.
  574. A specialized but useful call. Note that for success it returns 0,
  575. which is the opposite of almost all other TinyXml calls.
  576. */
  577. int QueryIntValue( int* value ) const;
  578. /// QueryDoubleValue examines the value string. See QueryIntValue().
  579. int QueryDoubleValue( double* value ) const;
  580. void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute.
  581. void SetValue( const char* _value ) { value = _value; } ///< Set the value.
  582. void SetIntValue( int value ); ///< Set the value from an integer.
  583. void SetDoubleValue( double value ); ///< Set the value from a double.
  584. #ifdef TIXML_USE_STL
  585. /// STL std::string form.
  586. void SetName( const std::string& _name )
  587. {
  588. StringToBuffer buf( _name );
  589. SetName ( buf.buffer ? buf.buffer : "error" );
  590. }
  591. /// STL std::string form.
  592. void SetValue( const std::string& _value )
  593. {
  594. StringToBuffer buf( _value );
  595. SetValue( buf.buffer ? buf.buffer : "error" );
  596. }
  597. #endif
  598. /// Get the next sibling attribute in the DOM. Returns null at end.
  599. const TiXmlAttribute* Next() const;
  600. TiXmlAttribute* Next();
  601. /// Get the previous sibling attribute in the DOM. Returns null at beginning.
  602. const TiXmlAttribute* Previous() const;
  603. TiXmlAttribute* Previous();
  604. bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; }
  605. bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; }
  606. bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; }
  607. /* Attribute parsing starts: first letter of the name
  608. returns: the next char after the value end quote
  609. */
  610. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  611. // Prints this Attribute to a FILE stream.
  612. virtual void Print( FILE* cfile, int depth ) const;
  613. virtual void StreamOut( TIXML_OSTREAM * out ) const;
  614. // [internal use]
  615. // Set the document pointer so the attribute can report errors.
  616. void SetDocument( TiXmlDocument* doc ) { document = doc; }
  617. private:
  618. TiXmlAttribute( const TiXmlAttribute& ); // not implemented.
  619. void operator=( const TiXmlAttribute& base ); // not allowed.
  620. TiXmlDocument* document; // A pointer back to a document, for error reporting.
  621. TIXML_STRING name;
  622. TIXML_STRING value;
  623. TiXmlAttribute* prev;
  624. TiXmlAttribute* next;
  625. };
  626. /* A class used to manage a group of attributes.
  627. It is only used internally, both by the ELEMENT and the DECLARATION.
  628. The set can be changed transparent to the Element and Declaration
  629. classes that use it, but NOT transparent to the Attribute
  630. which has to implement a next() and previous() method. Which makes
  631. it a bit problematic and prevents the use of STL.
  632. This version is implemented with circular lists because:
  633. - I like circular lists
  634. - it demonstrates some independence from the (typical) doubly linked list.
  635. */
  636. class TiXmlAttributeSet
  637. {
  638. public:
  639. TiXmlAttributeSet();
  640. ~TiXmlAttributeSet();
  641. void Add( TiXmlAttribute* attribute );
  642. void Remove( TiXmlAttribute* attribute );
  643. const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
  644. TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
  645. const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
  646. TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
  647. const TiXmlAttribute* Find( const char * name ) const;
  648. TiXmlAttribute* Find( const char * name );
  649. private:
  650. //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element),
  651. //*ME: this class must be also use a hidden/disabled copy-constructor !!!
  652. TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed
  653. void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute)
  654. TiXmlAttribute sentinel;
  655. };
  656. /** The element is a container class. It has a value, the element name,
  657. and can contain other elements, text, comments, and unknowns.
  658. Elements also contain an arbitrary number of attributes.
  659. */
  660. class TiXmlElement : public TiXmlNode
  661. {
  662. public:
  663. /// Construct an element.
  664. TiXmlElement (const char * in_value);
  665. #ifdef TIXML_USE_STL
  666. /// std::string constructor.
  667. TiXmlElement( const std::string& _value );
  668. #endif
  669. TiXmlElement( const TiXmlElement& );
  670. void operator=( const TiXmlElement& base );
  671. virtual ~TiXmlElement();
  672. /** Given an attribute name, Attribute() returns the value
  673. for the attribute of that name, or null if none exists.
  674. */
  675. const char* Attribute( const char* name ) const;
  676. /** Given an attribute name, Attribute() returns the value
  677. for the attribute of that name, or null if none exists.
  678. If the attribute exists and can be converted to an integer,
  679. the integer value will be put in the return 'i', if 'i'
  680. is non-null.
  681. */
  682. const char* Attribute( const char* name, int* i ) const;
  683. /** Given an attribute name, Attribute() returns the value
  684. for the attribute of that name, or null if none exists.
  685. If the attribute exists and can be converted to an double,
  686. the double value will be put in the return 'd', if 'd'
  687. is non-null.
  688. */
  689. const char* Attribute( const char* name, double* d ) const;
  690. /** QueryIntAttribute examines the attribute - it is an alternative to the
  691. Attribute() method with richer error checking.
  692. If the attribute is an integer, it is stored in 'value' and
  693. the call returns TIXML_SUCCESS. If it is not
  694. an integer, it returns TIXML_WRONG_TYPE. If the attribute
  695. does not exist, then TIXML_NO_ATTRIBUTE is returned.
  696. */
  697. int QueryIntAttribute( const char* name, int* value ) const;
  698. /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute().
  699. int QueryDoubleAttribute( const char* name, double* value ) const;
  700. /// QueryFloatAttribute examines the attribute - see QueryIntAttribute().
  701. int QueryDoubleAttribute( const char* name, float* value ) const {
  702. double d;
  703. int result = QueryDoubleAttribute( name, &d );
  704. *value = (float)d;
  705. return result;
  706. }
  707. /** Sets an attribute of name to a given value. The attribute
  708. will be created if it does not exist, or changed if it does.
  709. */
  710. void SetAttribute( const char* name, const char * value );
  711. #ifdef TIXML_USE_STL
  712. const char* Attribute( const std::string& name ) const { return Attribute( name.c_str() ); }
  713. const char* Attribute( const std::string& name, int* i ) const { return Attribute( name.c_str(), i ); }
  714. const char* Attribute( const std::string& name, double* d ) const { return Attribute( name.c_str(), d ); }
  715. int QueryIntAttribute( const std::string& name, int* value ) const { return QueryIntAttribute( name.c_str(), value ); }
  716. int QueryDoubleAttribute( const std::string& name, double* value ) const { return QueryDoubleAttribute( name.c_str(), value ); }
  717. /// STL std::string form.
  718. void SetAttribute( const std::string& name, const std::string& _value )
  719. {
  720. StringToBuffer n( name );
  721. StringToBuffer v( _value );
  722. if ( n.buffer && v.buffer )
  723. SetAttribute (n.buffer, v.buffer );
  724. }
  725. ///< STL std::string form.
  726. void SetAttribute( const std::string& name, int _value )
  727. {
  728. StringToBuffer n( name );
  729. if ( n.buffer )
  730. SetAttribute (n.buffer, _value);
  731. }
  732. #endif
  733. /** Sets an attribute of name to a given value. The attribute
  734. will be created if it does not exist, or changed if it does.
  735. */
  736. void SetAttribute( const char * name, int value );
  737. /** Sets an attribute of name to a given value. The attribute
  738. will be created if it does not exist, or changed if it does.
  739. */
  740. void SetDoubleAttribute( const char * name, double value );
  741. /** Deletes an attribute with the given name.
  742. */
  743. void RemoveAttribute( const char * name );
  744. #ifdef TIXML_USE_STL
  745. void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form.
  746. #endif
  747. const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element.
  748. TiXmlAttribute* FirstAttribute() { return attributeSet.First(); }
  749. const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element.
  750. TiXmlAttribute* LastAttribute() { return attributeSet.Last(); }
  751. /// Creates a new Element and returns it - the returned element is a copy.
  752. virtual TiXmlNode* Clone() const;
  753. // Print the Element to a FILE stream.
  754. virtual void Print( FILE* cfile, int depth ) const;
  755. /* Attribtue parsing starts: next char past '<'
  756. returns: next char past '>'
  757. */
  758. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  759. protected:
  760. void CopyTo( TiXmlElement* target ) const;
  761. void ClearThis(); // like clear, but initializes 'this' object as well
  762. // Used to be public [internal use]
  763. #ifdef TIXML_USE_STL
  764. virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
  765. #endif
  766. virtual void StreamOut( TIXML_OSTREAM * out ) const;
  767. /* [internal use]
  768. Reads the "value" of the element -- another element, or text.
  769. This should terminate with the current end tag.
  770. */
  771. const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding );
  772. private:
  773. TiXmlAttributeSet attributeSet;
  774. };
  775. /** An XML comment.
  776. */
  777. class TiXmlComment : public TiXmlNode
  778. {
  779. public:
  780. /// Constructs an empty comment.
  781. TiXmlComment() : TiXmlNode( TiXmlNode::COMMENT ) {}
  782. TiXmlComment( const TiXmlComment& );
  783. void operator=( const TiXmlComment& base );
  784. virtual ~TiXmlComment() {}
  785. /// Returns a copy of this Comment.
  786. virtual TiXmlNode* Clone() const;
  787. /// Write this Comment to a FILE stream.
  788. virtual void Print( FILE* cfile, int depth ) const;
  789. /* Attribtue parsing starts: at the ! of the !--
  790. returns: next char past '>'
  791. */
  792. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  793. protected:
  794. void CopyTo( TiXmlComment* target ) const;
  795. // used to be public
  796. #ifdef TIXML_USE_STL
  797. virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
  798. #endif
  799. virtual void StreamOut( TIXML_OSTREAM * out ) const;
  800. private:
  801. };
  802. /** XML text. Contained in an element.
  803. */
  804. class TiXmlText : public TiXmlNode
  805. {
  806. friend class TiXmlElement;
  807. public:
  808. /// Constructor.
  809. TiXmlText (const char * initValue) : TiXmlNode (TiXmlNode::TEXT)
  810. {
  811. SetValue( initValue );
  812. }
  813. virtual ~TiXmlText() {}
  814. #ifdef TIXML_USE_STL
  815. /// Constructor.
  816. TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TEXT)
  817. {
  818. SetValue( initValue );
  819. }
  820. #endif
  821. TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TEXT ) { copy.CopyTo( this ); }
  822. void operator=( const TiXmlText& base ) { base.CopyTo( this ); }
  823. /// Write this text object to a FILE stream.
  824. virtual void Print( FILE* cfile, int depth ) const;
  825. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  826. protected :
  827. /// [internal use] Creates a new Element and returns it.
  828. virtual TiXmlNode* Clone() const;
  829. void CopyTo( TiXmlText* target ) const;
  830. virtual void StreamOut ( TIXML_OSTREAM * out ) const;
  831. bool Blank() const; // returns true if all white space and new lines
  832. // [internal use]
  833. #ifdef TIXML_USE_STL
  834. virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
  835. #endif
  836. private:
  837. };
  838. /** In correct XML the declaration is the first entry in the file.
  839. @verbatim
  840. <?xml version="1.0" standalone="yes"?>
  841. @endverbatim
  842. TinyXml will happily read or write files without a declaration,
  843. however. There are 3 possible attributes to the declaration:
  844. version, encoding, and standalone.
  845. Note: In this version of the code, the attributes are
  846. handled as special cases, not generic attributes, simply
  847. because there can only be at most 3 and they are always the same.
  848. */
  849. class TiXmlDeclaration : public TiXmlNode
  850. {
  851. public:
  852. /// Construct an empty declaration.
  853. TiXmlDeclaration() : TiXmlNode( TiXmlNode::DECLARATION ) {}
  854. #ifdef TIXML_USE_STL
  855. /// Constructor.
  856. TiXmlDeclaration( const std::string& _version,
  857. const std::string& _encoding,
  858. const std::string& _standalone );
  859. #endif
  860. /// Construct.
  861. TiXmlDeclaration( const char* _version,
  862. const char* _encoding,
  863. const char* _standalone );
  864. TiXmlDeclaration( const TiXmlDeclaration& copy );
  865. void operator=( const TiXmlDeclaration& copy );
  866. virtual ~TiXmlDeclaration() {}
  867. /// Version. Will return an empty string if none was found.
  868. const char *Version() const { return version.c_str (); }
  869. /// Encoding. Will return an empty string if none was found.
  870. const char *Encoding() const { return encoding.c_str (); }
  871. /// Is this a standalone document?
  872. const char *Standalone() const { return standalone.c_str (); }
  873. /// Creates a copy of this Declaration and returns it.
  874. virtual TiXmlNode* Clone() const;
  875. /// Print this declaration to a FILE stream.
  876. virtual void Print( FILE* cfile, int depth ) const;
  877. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  878. protected:
  879. void CopyTo( TiXmlDeclaration* target ) const;
  880. // used to be public
  881. #ifdef TIXML_USE_STL
  882. virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
  883. #endif
  884. virtual void StreamOut ( TIXML_OSTREAM * out) const;
  885. private:
  886. TIXML_STRING version;
  887. TIXML_STRING encoding;
  888. TIXML_STRING standalone;
  889. };
  890. /** Any tag that tinyXml doesn't recognize is saved as an
  891. unknown. It is a tag of text, but should not be modified.
  892. It will be written back to the XML, unchanged, when the file
  893. is saved.
  894. DTD tags get thrown into TiXmlUnknowns.
  895. */
  896. class TiXmlUnknown : public TiXmlNode
  897. {
  898. public:
  899. TiXmlUnknown() : TiXmlNode( TiXmlNode::UNKNOWN ) {}
  900. virtual ~TiXmlUnknown() {}
  901. TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::UNKNOWN ) { copy.CopyTo( this ); }
  902. void operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); }
  903. /// Creates a copy of this Unknown and returns it.
  904. virtual TiXmlNode* Clone() const;
  905. /// Print this Unknown to a FILE stream.
  906. virtual void Print( FILE* cfile, int depth ) const;
  907. virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
  908. protected:
  909. void CopyTo( TiXmlUnknown* target ) const;
  910. #ifdef TIXML_USE_STL
  911. virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
  912. #endif
  913. virtual void StreamOut ( TIXML_OSTREAM * out ) const;
  914. private:
  915. };
  916. /** Always the top level node. A document binds together all the
  917. XML pieces. It can be saved, loaded, and printed to the screen.
  918. The 'value' of a document node is the xml file name.
  919. */
  920. class TiXmlDocument : public TiXmlNode
  921. {
  922. public:
  923. /// Create an empty document, that has no name.
  924. TiXmlDocument();
  925. /// Create a document with a name. The name of the document is also the filename of the xml.
  926. TiXmlDocument( const char * documentName );
  927. #ifdef TIXML_USE_STL
  928. /// Constructor.
  929. TiXmlDocument( const std::string& documentName );
  930. #endif
  931. TiXmlDocument( const TiXmlDocument& copy );
  932. void operator=( const TiXmlDocument& copy );
  933. virtual ~TiXmlDocument() {}
  934. /** Load a file using the current document value.
  935. Returns true if successful. Will delete any existing
  936. document data before loading.
  937. */
  938. bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
  939. /// Save a file using the current document value. Returns true if successful.
  940. bool SaveFile() const;
  941. /// Load a file using the given filename. Returns true if successful.
  942. bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
  943. /// Save a file using the given filename. Returns true if successful.
  944. bool SaveFile( const char * filename ) const;
  945. #ifdef TIXML_USE_STL
  946. bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version.
  947. {
  948. StringToBuffer f( filename );
  949. return ( f.buffer && LoadFile( f.buffer, encoding ));
  950. }
  951. bool SaveFile( const std::string& filename ) const ///< STL std::string version.
  952. {
  953. StringToBuffer f( filename );
  954. return ( f.buffer && SaveFile( f.buffer ));
  955. }
  956. #endif
  957. /** Parse the given null terminated block of xml data. Passing in an encoding to this
  958. method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml
  959. to use that encoding, regardless of what TinyXml might otherwise try to detect.
  960. */
  961. virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
  962. /** Get the root element -- the only top level element -- of the document.
  963. In well formed XML, there should only be one. TinyXml is tolerant of
  964. multiple elements at the document level.
  965. */
  966. const TiXmlElement* RootElement() const { return FirstChildElement(); }
  967. TiXmlElement* RootElement() { return FirstChildElement(); }
  968. /** If an error occurs, Error will be set to true. Also,
  969. - The ErrorId() will contain the integer identifier of the error (not generally useful)
  970. - The ErrorDesc() method will return the name of the error. (very useful)
  971. - The ErrorRow() and ErrorCol() will return the location of the error (if known)
  972. */
  973. bool Error() const { return error; }
  974. /// Contains a textual (english) description of the error if one occurs.
  975. const char * ErrorDesc() const { return errorDesc.c_str (); }
  976. /** Generally, you probably want the error string ( ErrorDesc() ). But if you
  977. prefer the ErrorId, this function will fetch it.
  978. */
  979. const int ErrorId() const { return errorId; }
  980. /** Returns the location (if known) of the error. The first column is column 1,
  981. and the first row is row 1. A value of 0 means the row and column wasn't applicable
  982. (memory errors, for example, have no row/column) or the parser lost the error. (An
  983. error in the error reporting, in that case.)
  984. @sa SetTabSize, Row, Column
  985. */
  986. int ErrorRow() { return errorLocation.row+1; }
  987. int ErrorCol() { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow()
  988. /** By calling this method, with a tab size
  989. greater than 0, the row and column of each node and attribute is stored
  990. when the file is loaded. Very useful for tracking the DOM back in to
  991. the source file.
  992. The tab size is required for calculating the location of nodes. If not
  993. set, the default of 4 is used. The tabsize is set per document. Setting
  994. the tabsize to 0 disables row/column tracking.
  995. Note that row and column tracking is not supported when using operator>>.
  996. The tab size needs to be enabled before the parse or load. Correct usage:
  997. @verbatim
  998. TiXmlDocument doc;
  999. doc.SetTabSize( 8 );
  1000. doc.Load( "myfile.xml" );
  1001. @endverbatim
  1002. @sa Row, Column
  1003. */
  1004. void SetTabSize( int _tabsize ) { tabsize = _tabsize; }
  1005. int TabSize() const { return tabsize; }
  1006. /** If you have handled the error, it can be reset with this call. The error
  1007. state is automatically cleared if you Parse a new XML block.
  1008. */
  1009. void ClearError() { error = false;
  1010. errorId = 0;
  1011. errorDesc = "";
  1012. errorLocation.row = errorLocation.col = 0;
  1013. //errorLocation.last = 0;
  1014. }
  1015. /** Dump the document to standard out. */
  1016. void Print() const { Print( stdout, 0 ); }
  1017. /// Print this Document to a FILE stream.
  1018. virtual void Print( FILE* cfile, int depth = 0 ) const;
  1019. // [internal use]
  1020. void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding );
  1021. protected :
  1022. virtual void StreamOut ( TIXML_OSTREAM * out) const;
  1023. // [internal use]
  1024. virtual TiXmlNode* Clone() const;
  1025. #ifdef TIXML_USE_STL
  1026. virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
  1027. #endif
  1028. private:
  1029. void CopyTo( TiXmlDocument* target ) const;
  1030. bool error;
  1031. int errorId;
  1032. TIXML_STRING errorDesc;
  1033. int tabsize;
  1034. TiXmlCursor errorLocation;
  1035. };
  1036. /**
  1037. A TiXmlHandle is a class that wraps a node pointer with null checks; this is
  1038. an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml
  1039. DOM structure. It is a separate utility class.
  1040. Take an example:
  1041. @verbatim
  1042. <Document>
  1043. <Element attributeA = "valueA">
  1044. <Child attributeB = "value1" />
  1045. <Child attributeB = "value2" />
  1046. </Element>
  1047. <Document>
  1048. @endverbatim
  1049. Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
  1050. easy to write a *lot* of code that looks like:
  1051. @verbatim
  1052. TiXmlElement* root = document.FirstChildElement( "Document" );
  1053. if ( root )
  1054. {
  1055. TiXmlElement* element = root->FirstChildElement( "Element" );
  1056. if ( element )
  1057. {
  1058. TiXmlElement* child = element->FirstChildElement( "Child" );
  1059. if ( child )
  1060. {
  1061. TiXmlElement* child2 = child->NextSiblingElement( "Child" );
  1062. if ( child2 )
  1063. {
  1064. // Finally do something useful.
  1065. @endverbatim
  1066. And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity
  1067. of such code. A TiXmlHandle checks for null pointers so it is perfectly safe
  1068. and correct to use:
  1069. @verbatim
  1070. TiXmlHandle docHandle( &document );
  1071. TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).Element();
  1072. if ( child2 )
  1073. {
  1074. // do something useful
  1075. @endverbatim
  1076. Which is MUCH more concise and useful.
  1077. It is also safe to copy handles - internally they are nothing more than node pointers.
  1078. @verbatim
  1079. TiXmlHandle handleCopy = handle;
  1080. @endverbatim
  1081. What they should not be used for is iteration:
  1082. @verbatim
  1083. int i=0;
  1084. while ( true )
  1085. {
  1086. TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).Element();
  1087. if ( !child )
  1088. break;
  1089. // do something
  1090. ++i;
  1091. }
  1092. @endverbatim
  1093. It seems reasonable, but it is in fact two embedded while loops. The Child method is
  1094. a linear walk to find the element, so this code would iterate much more than it needs
  1095. to. Instead, prefer:
  1096. @verbatim
  1097. TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).Element();
  1098. for( child; child; child=child->NextSiblingElement() )
  1099. {
  1100. // do something
  1101. }
  1102. @endverbatim
  1103. */
  1104. class TiXmlHandle
  1105. {
  1106. public:
  1107. /// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
  1108. TiXmlHandle( TiXmlNode* node ) { this->node = node; }
  1109. /// Copy constructor
  1110. TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; }
  1111. TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; }
  1112. /// Return a handle to the first child node.
  1113. TiXmlHandle FirstChild() const;
  1114. /// Return a handle to the first child node with the given name.
  1115. TiXmlHandle FirstChild( const char * value ) const;
  1116. /// Return a handle to the first child element.
  1117. TiXmlHandle FirstChildElement() const;
  1118. /// Return a handle to the first child element with the given name.
  1119. TiXmlHandle FirstChildElement( const char * value ) const;
  1120. /** Return a handle to the "index" child with the given name.
  1121. The first child is 0, the second 1, etc.
  1122. */
  1123. TiXmlHandle Child( const char* value, int index ) const;
  1124. /** Return a handle to the "index" child.
  1125. The first child is 0, the second 1, etc.
  1126. */
  1127. TiXmlHandle Child( int index ) const;
  1128. /** Return a handle to the "index" child element with the given name.
  1129. The first child element is 0, the second 1, etc. Note that only TiXmlElements
  1130. are indexed: other types are not counted.
  1131. */
  1132. TiXmlHandle ChildElement( const char* value, int index ) const;
  1133. /** Return a handle to the "index" child element.
  1134. The first child element is 0, the second 1, etc. Note that only TiXmlElements
  1135. are indexed: other types are not counted.
  1136. */
  1137. TiXmlHandle ChildElement( int index ) const;
  1138. #ifdef TIXML_USE_STL
  1139. TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); }
  1140. TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); }
  1141. TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); }
  1142. TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); }
  1143. #endif
  1144. /// Return the handle as a TiXmlNode. This may return null.
  1145. TiXmlNode* Node() const { return node; }
  1146. /// Return the handle as a TiXmlElement. This may return null.
  1147. TiXmlElement* Element() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); }
  1148. /// Return the handle as a TiXmlText. This may return null.
  1149. TiXmlText* Text() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); }
  1150. /// Return the handle as a TiXmlUnknown. This may return null;
  1151. TiXmlUnknown* Unknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); }
  1152. private:
  1153. TiXmlNode* node;
  1154. };
  1155. #ifdef _MSC_VER
  1156. #pragma warning( default : 4530 )
  1157. #pragma warning( default : 4786 )
  1158. #endif
  1159. #endif