Debian Codegraph @

examples/tinyxml/tinyxml.h

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