2
www.sourceforge.net/projects/tinyxml
3
Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com)
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.
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:
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.
18
2. Altered source versions must be plainly marked as such, and
19
must not be misrepresented as being the original software.
21
3. This notice may not be removed or altered from any source
26
#ifndef TINYXML_INCLUDED
27
#define TINYXML_INCLUDED
32
#pragma warning( push )
33
#pragma warning( disable : 4530 )
34
#pragma warning( disable : 4786 )
44
#if defined( _DEBUG ) && !defined( DEBUG )
52
#define TIXML_STRING std::string
55
#define TIXML_STRING TiXmlString
58
// Deprecated library function hell. Compilers want to use the
59
// new safe versions. This probably doesn't fully address the problem,
60
// but it gets closer. There are too many compilers for me to fully
61
// test. If you get compilation troubles, undefine TIXML_SAFE
65
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
66
// Microsoft visual studio, version 2005 and higher.
67
#define TIXML_SNPRINTF _snprintf_s
68
#define TIXML_SNSCANF _snscanf_s
69
#define TIXML_SSCANF sscanf_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
#define TIXML_SSCANF sscanf
76
#elif defined(__GNUC__) && (__GNUC__ >= 3 )
77
// GCC version 3 and higher.s
78
//#warning( "Using sn* functions." )
79
#define TIXML_SNPRINTF snprintf
80
#define TIXML_SNSCANF snscanf
81
#define TIXML_SSCANF sscanf
83
#define TIXML_SSCANF sscanf
93
class TiXmlDeclaration;
94
class TiXmlParsingData;
96
const int TIXML_MAJOR_VERSION = 2;
97
const int TIXML_MINOR_VERSION = 5;
98
const int TIXML_PATCH_VERSION = 3;
100
/* Internal structure for tracking location of items
105
TiXmlCursor() { Clear(); }
106
void Clear() { row = col = -1; }
114
If you call the Accept() method, it requires being passed a TiXmlVisitor
115
class to handle callbacks. For nodes that contain other nodes (Document, Element)
116
you will get called with a VisitEnter/VisitExit pair. Nodes that are always leaves
117
are simple called with Visit().
119
If you return 'true' from a Visit method, recursive parsing will continue. If you return
120
false, <b>no children of this node or its sibilings</b> will be Visited.
122
All flavors of Visit methods have a default implementation that returns 'true' (continue
123
visiting). You need to only override methods that are interesting to you.
125
Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting.
127
You should never change the document from a callback.
129
@sa TiXmlNode::Accept()
134
virtual ~TiXmlVisitor() {}
136
/// Visit a document.
137
virtual bool VisitEnter( const TiXmlDocument& /*doc*/ ) { return true; }
138
/// Visit a document.
139
virtual bool VisitExit( const TiXmlDocument& /*doc*/ ) { return true; }
141
/// Visit an element.
142
virtual bool VisitEnter( const TiXmlElement& /*element*/, const TiXmlAttribute* /*firstAttribute*/ ) { return true; }
143
/// Visit an element.
144
virtual bool VisitExit( const TiXmlElement& /*element*/ ) { return true; }
146
/// Visit a declaration
147
virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) { return true; }
148
/// Visit a text node
149
virtual bool Visit( const TiXmlText& /*text*/ ) { return true; }
150
/// Visit a comment node
151
virtual bool Visit( const TiXmlComment& /*comment*/ ) { return true; }
152
/// Visit an unknow node
153
virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) { return true; }
156
// Only used by Attribute::Query functions
165
// Used by the parsing routines.
168
TIXML_ENCODING_UNKNOWN,
170
TIXML_ENCODING_LEGACY
173
const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN;
175
/** TiXmlBase is a base class for every class in TinyXml.
176
It does little except to establish that TinyXml classes
177
can be printed and provide some utility functions.
179
In XML, the document and elements can contain
180
other elements and other types of nodes.
183
A Document can contain: Element (container or leaf)
188
An Element can contain: Element (container or leaf)
190
Attributes (not on tree)
194
A Decleration contains: Attributes (not on tree)
199
friend class TiXmlNode;
200
friend class TiXmlElement;
201
friend class TiXmlDocument;
204
TiXmlBase() : userData(0) {}
205
virtual ~TiXmlBase() {}
207
/** All TinyXml classes can print themselves to a filestream
208
or the string class (TiXmlString in non-STL mode, std::string
209
in STL mode.) Either or both cfile and str can be null.
211
This is a formatted print, and will insert
214
(For an unformatted stream, use the << operator.)
216
virtual void Print( FILE* cfile, int depth ) const = 0;
218
/** The world does not agree on whether white space should be kept or
219
not. In order to make everyone happy, these global, static functions
220
are provided to set whether or not TinyXml will condense all white space
221
into a single space or not. The default is to condense. Note changing this
222
value is not thread safe.
224
static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; }
226
/// Return the current white space setting.
227
static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; }
229
/** Return the position, in the original source file, of this node or attribute.
230
The row and column are 1-based. (That is the first row and first column is
231
1,1). If the returns values are 0 or less, then the parser does not have
232
a row and column value.
234
Generally, the row and column value will be set when the TiXmlDocument::Load(),
235
TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set
236
when the DOM was created from operator>>.
238
The values reflect the initial load. Once the DOM is modified programmatically
239
(by adding or changing nodes and attributes) the new values will NOT update to
240
reflect changes in the document.
242
There is a minor performance cost to computing the row and column. Computation
243
can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value.
245
@sa TiXmlDocument::SetTabSize()
247
int Row() const { return location.row + 1; }
248
int Column() const { return location.col + 1; } ///< See Row()
250
void SetUserData( void* user ) { userData = user; } ///< Set a pointer to arbitrary user data.
251
void* GetUserData() { return userData; } ///< Get a pointer to arbitrary user data.
252
const void* GetUserData() const { return userData; } ///< Get a pointer to arbitrary user data.
254
// Table that returs, for a given lead byte, the total number of bytes
255
// in the UTF-8 sequence.
256
static const int utf8ByteTable[256];
258
virtual const char* Parse( const char* p,
259
TiXmlParsingData* data,
260
TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0;
262
/** Expands entities in a string. Note this should not contian the tag's '<', '>', etc,
263
or they will be transformed into entities!
265
static void EncodeString( const TIXML_STRING& str, TIXML_STRING* out );
271
TIXML_ERROR_OPENING_FILE,
272
TIXML_ERROR_OUT_OF_MEMORY,
273
TIXML_ERROR_PARSING_ELEMENT,
274
TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME,
275
TIXML_ERROR_READING_ELEMENT_VALUE,
276
TIXML_ERROR_READING_ATTRIBUTES,
277
TIXML_ERROR_PARSING_EMPTY,
278
TIXML_ERROR_READING_END_TAG,
279
TIXML_ERROR_PARSING_UNKNOWN,
280
TIXML_ERROR_PARSING_COMMENT,
281
TIXML_ERROR_PARSING_DECLARATION,
282
TIXML_ERROR_DOCUMENT_EMPTY,
283
TIXML_ERROR_EMBEDDED_NULL,
284
TIXML_ERROR_PARSING_CDATA,
285
TIXML_ERROR_DOCUMENT_TOP_ONLY,
287
TIXML_ERROR_STRING_COUNT
292
static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding );
293
inline static bool IsWhiteSpace( char c )
295
return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' );
297
inline static bool IsWhiteSpace( int c )
300
return IsWhiteSpace( (char) c );
301
return false; // Again, only truly correct for English/Latin...but usually works.
305
static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag );
306
static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag );
309
/* Reads an XML name into the string provided. Returns
310
a pointer just past the last character of the name,
311
or 0 if the function has an error.
313
static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding );
315
/* Reads text. Returns a pointer past the given end tag.
316
Wickedly complex options, but it keeps the (sensitive) code in one place.
318
static const char* ReadText( const char* in, // where to start
319
TIXML_STRING* text, // the string read
320
bool ignoreWhiteSpace, // whether to keep the white space
321
const char* endTag, // what ends this text
322
bool ignoreCase, // whether to ignore case in the end tag
323
TiXmlEncoding encoding ); // the current encoding
325
// If an entity has been found, transform it into a character.
326
static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding );
328
// Get a character, while interpreting entities.
329
// The length can be from 0 to 4 bytes.
330
inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding )
333
if ( encoding == TIXML_ENCODING_UTF8 )
335
*length = utf8ByteTable[ *((const unsigned char*)p) ];
336
assert( *length >= 0 && *length < 5 );
346
return GetEntity( p, _value, length, encoding );
352
//strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe),
353
// and the null terminator isn't needed
354
for( int i=0; p[i] && i<*length; ++i ) {
357
return p + (*length);
366
// Return true if the next characters in the stream are any of the endTag sequences.
367
// Ignore case only works for english, and should only be relied on when comparing
368
// to English words: StringEqual( p, "version", true ) is fine.
369
static bool StringEqual( const char* p,
372
TiXmlEncoding encoding );
374
static const char* errorString[ TIXML_ERROR_STRING_COUNT ];
376
TiXmlCursor location;
378
/// Field containing a generic user pointer
381
// None of these methods are reliable for any language except English.
382
// Good for approximation, not great for accuracy.
383
static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding );
384
static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding );
385
inline static int ToLower( int v, TiXmlEncoding encoding )
387
if ( encoding == TIXML_ENCODING_UTF8 )
389
if ( v < 128 ) return tolower( v );
397
static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
400
TiXmlBase( const TiXmlBase& ); // not implemented.
401
void operator=( const TiXmlBase& base ); // not allowed.
406
unsigned int strLength;
412
MAX_ENTITY_LENGTH = 6
415
static Entity entity[ NUM_ENTITY ];
416
static bool condenseWhiteSpace;
420
/** The parent class for everything in the Document Object Model.
421
(Except for attributes).
422
Nodes have siblings, a parent, and children. A node can be
423
in a document, or stand on its own. The type of a TiXmlNode
424
can be queried, and it can be cast to its more defined type.
426
class TiXmlNode : public TiXmlBase
428
friend class TiXmlDocument;
429
friend class TiXmlElement;
434
/** An input stream operator, for every class. Tolerant of newlines and
435
formatting, but doesn't expect them.
437
friend std::istream& operator >> (std::istream& in, TiXmlNode& base);
439
/** An output stream operator, for every class. Note that this outputs
440
without any newlines or formatting, as opposed to Print(), which
441
includes tabs and new lines.
443
The operator<< and operator>> are not completely symmetric. Writing
444
a node to a stream is very well defined. You'll get a nice stream
445
of output, without any extra whitespace or newlines.
447
But reading is not as well defined. (As it always is.) If you create
448
a TiXmlElement (for example) and read that from an input stream,
449
the text needs to define an element or junk will result. This is
450
true of all input streams, but it's worth keeping in mind.
452
A TiXmlDocument will read nodes until it reads a root element, and
453
all the children of that root element.
455
friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base);
457
/// Appends the XML node or attribute to a std::string.
458
friend std::string& operator<< (std::string& out, const TiXmlNode& base );
462
/** The types of XML nodes supported by TinyXml. (All the
463
unsupported types are picked up by UNKNOWN.)
476
virtual ~TiXmlNode();
478
/** The meaning of 'value' changes for the specific type of
481
Document: filename of the xml file
482
Element: name of the element
483
Comment: the comment text
484
Unknown: the tag contents
485
Text: the text string
488
The subclasses will wrap this function.
490
const char *Value() const { return value.c_str (); }
493
/** Return Value() as a std::string. If you only use STL,
494
this is more efficient than calling Value().
495
Only available in STL mode.
497
const std::string& ValueStr() const { return value; }
500
const TIXML_STRING& ValueTStr() const { return value; }
502
/** Changes the value of the node. Defined as:
504
Document: filename of the xml file
505
Element: name of the element
506
Comment: the comment text
507
Unknown: the tag contents
508
Text: the text string
511
void SetValue(const char * _value) { value = _value;}
514
/// STL std::string form.
515
void SetValue( const std::string& _value ) { value = _value; }
518
/// Delete all the children of this node. Does not affect 'this'.
521
/// One step up the DOM.
522
TiXmlNode* Parent() { return parent; }
523
const TiXmlNode* Parent() const { return parent; }
525
const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children.
526
TiXmlNode* FirstChild() { return firstChild; }
527
const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found.
528
/// The first child of this node with the matching 'value'. Will be null if none found.
529
TiXmlNode* FirstChild( const char * _value ) {
530
// Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe)
531
// call the method, cast the return back to non-const.
532
return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value ));
534
const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children.
535
TiXmlNode* LastChild() { return lastChild; }
537
const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children.
538
TiXmlNode* LastChild( const char * _value ) {
539
return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value ));
543
const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form.
544
TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form.
545
const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form.
546
TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form.
549
/** An alternate way to walk the children of a node.
550
One way to iterate over nodes is:
552
for( child = parent->FirstChild(); child; child = child->NextSibling() )
555
IterateChildren does the same thing with the syntax:
558
while( child = parent->IterateChildren( child ) )
561
IterateChildren takes the previous child as input and finds
562
the next one. If the previous child is null, it returns the
563
first. IterateChildren will return null when done.
565
const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const;
566
TiXmlNode* IterateChildren( const TiXmlNode* previous ) {
567
return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) );
570
/// This flavor of IterateChildren searches for children with a particular 'value'
571
const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const;
572
TiXmlNode* IterateChildren( const char * _value, const TiXmlNode* previous ) {
573
return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( _value, previous ) );
577
const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
578
TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
581
/** Add a new node related to this. Adds a child past the LastChild.
582
Returns a pointer to the new object or NULL if an error occured.
584
TiXmlNode* InsertEndChild( const TiXmlNode& addThis );
587
/** Add a new node related to this. Adds a child past the LastChild.
589
NOTE: the node to be added is passed by pointer, and will be
590
henceforth owned (and deleted) by tinyXml. This method is efficient
591
and avoids an extra copy, but should be used with care as it
592
uses a different memory model than the other insert functions.
596
TiXmlNode* LinkEndChild( TiXmlNode* addThis );
598
/** Add a new node related to this. Adds a child before the specified child.
599
Returns a pointer to the new object or NULL if an error occured.
601
TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis );
603
/** Add a new node related to this. Adds a child after the specified child.
604
Returns a pointer to the new object or NULL if an error occured.
606
TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis );
608
/** Replace a child of this node.
609
Returns a pointer to the new object or NULL if an error occured.
611
TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis );
613
/// Delete a child of this node.
614
bool RemoveChild( TiXmlNode* removeThis );
616
/// Navigate to a sibling node.
617
const TiXmlNode* PreviousSibling() const { return prev; }
618
TiXmlNode* PreviousSibling() { return prev; }
620
/// Navigate to a sibling node.
621
const TiXmlNode* PreviousSibling( const char * ) const;
622
TiXmlNode* PreviousSibling( const char *_prev ) {
623
return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->PreviousSibling( _prev ) );
627
const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
628
TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
629
const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form.
630
TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form.
633
/// Navigate to a sibling node.
634
const TiXmlNode* NextSibling() const { return next; }
635
TiXmlNode* NextSibling() { return next; }
637
/// Navigate to a sibling node with the given 'value'.
638
const TiXmlNode* NextSibling( const char * ) const;
639
TiXmlNode* NextSibling( const char* _next ) {
640
return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->NextSibling( _next ) );
643
/** Convenience function to get through elements.
644
Calls NextSibling and ToElement. Will skip all non-Element
645
nodes. Returns 0 if there is not another element.
647
const TiXmlElement* NextSiblingElement() const;
648
TiXmlElement* NextSiblingElement() {
649
return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement() );
652
/** Convenience function to get through elements.
653
Calls NextSibling and ToElement. Will skip all non-Element
654
nodes. Returns 0 if there is not another element.
656
const TiXmlElement* NextSiblingElement( const char * ) const;
657
TiXmlElement* NextSiblingElement( const char *_next ) {
658
return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement( _next ) );
662
const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
663
TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
666
/// Convenience function to get through elements.
667
const TiXmlElement* FirstChildElement() const;
668
TiXmlElement* FirstChildElement() {
669
return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement() );
672
/// Convenience function to get through elements.
673
const TiXmlElement* FirstChildElement( const char * _value ) const;
674
TiXmlElement* FirstChildElement( const char * _value ) {
675
return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement( _value ) );
679
const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
680
TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
683
/** Query the type (as an enumerated value, above) of this node.
684
The possible types are: DOCUMENT, ELEMENT, COMMENT,
685
UNKNOWN, TEXT, and DECLARATION.
687
int Type() const { return type; }
689
/** Return a pointer to the Document this node lives in.
690
Returns null if not in a document.
692
const TiXmlDocument* GetDocument() const;
693
TiXmlDocument* GetDocument() {
694
return const_cast< TiXmlDocument* >( (const_cast< const TiXmlNode* >(this))->GetDocument() );
697
/// Returns true if this node has no children.
698
bool NoChildren() const { return !firstChild; }
700
virtual const TiXmlDocument* ToDocument() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
701
virtual const TiXmlElement* ToElement() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
702
virtual const TiXmlComment* ToComment() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
703
virtual const TiXmlUnknown* ToUnknown() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
704
virtual const TiXmlText* ToText() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
705
virtual const TiXmlDeclaration* ToDeclaration() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
707
virtual TiXmlDocument* ToDocument() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
708
virtual TiXmlElement* ToElement() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
709
virtual TiXmlComment* ToComment() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
710
virtual TiXmlUnknown* ToUnknown() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
711
virtual TiXmlText* ToText() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
712
virtual TiXmlDeclaration* ToDeclaration() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
714
/** Create an exact duplicate of this node and return it. The memory must be deleted
717
virtual TiXmlNode* Clone() const = 0;
719
/** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the
720
XML tree will be conditionally visited and the host will be called back
721
via the TiXmlVisitor interface.
723
This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse
724
the XML for the callbacks, so the performance of TinyXML is unchanged by using this
725
interface versus any other.)
727
The interface has been based on ideas from:
729
- http://www.saxproject.org/
730
- http://c2.com/cgi/wiki?HierarchicalVisitorPattern
732
Which are both good references for "visiting".
734
An example of using Accept():
736
TiXmlPrinter printer;
737
tinyxmlDoc.Accept( &printer );
738
const char* xmlcstr = printer.CStr();
741
virtual bool Accept( TiXmlVisitor* visitor ) const = 0;
744
TiXmlNode( NodeType _type );
746
// Copy to the allocated object. Shared functionality between Clone, Copy constructor,
747
// and the assignment operator.
748
void CopyTo( TiXmlNode* target ) const;
751
// The real work of the input operator.
752
virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0;
755
// Figure out what is at *p, and parse it. Returns null if it is not an xml node.
756
TiXmlNode* Identify( const char* start, TiXmlEncoding encoding );
761
TiXmlNode* firstChild;
762
TiXmlNode* lastChild;
770
TiXmlNode( const TiXmlNode& ); // not implemented.
771
void operator=( const TiXmlNode& base ); // not allowed.
775
/** An attribute is a name-value pair. Elements have an arbitrary
776
number of attributes, each with a unique name.
778
@note The attributes are not TiXmlNodes, since they are not
779
part of the tinyXML document object model. There are other
780
suggested ways to look at this problem.
782
class TiXmlAttribute : public TiXmlBase
784
friend class TiXmlAttributeSet;
787
/// Construct an empty attribute.
788
TiXmlAttribute() : TiXmlBase()
795
/// std::string constructor.
796
TiXmlAttribute( const std::string& _name, const std::string& _value )
805
/// Construct an attribute with a name and value.
806
TiXmlAttribute( const char * _name, const char * _value )
814
const char* Name() const { return name.c_str(); } ///< Return the name of this attribute.
815
const char* Value() const { return value.c_str(); } ///< Return the value of this attribute.
817
const std::string& ValueStr() const { return value; } ///< Return the value of this attribute.
819
int IntValue() const; ///< Return the value of this attribute, converted to an integer.
820
double DoubleValue() const; ///< Return the value of this attribute, converted to a double.
822
// Get the tinyxml string representation
823
const TIXML_STRING& NameTStr() const { return name; }
825
/** QueryIntValue examines the value string. It is an alternative to the
826
IntValue() method with richer error checking.
827
If the value is an integer, it is stored in 'value' and
828
the call returns TIXML_SUCCESS. If it is not
829
an integer, it returns TIXML_WRONG_TYPE.
831
A specialized but useful call. Note that for success it returns 0,
832
which is the opposite of almost all other TinyXml calls.
834
int QueryIntValue( int* _value ) const;
835
/// QueryDoubleValue examines the value string. See QueryIntValue().
836
int QueryDoubleValue( double* _value ) const;
838
void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute.
839
void SetValue( const char* _value ) { value = _value; } ///< Set the value.
841
void SetIntValue( int _value ); ///< Set the value from an integer.
842
void SetDoubleValue( double _value ); ///< Set the value from a double.
845
/// STL std::string form.
846
void SetName( const std::string& _name ) { name = _name; }
847
/// STL std::string form.
848
void SetValue( const std::string& _value ) { value = _value; }
851
/// Get the next sibling attribute in the DOM. Returns null at end.
852
const TiXmlAttribute* Next() const;
853
TiXmlAttribute* Next() {
854
return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Next() );
857
/// Get the previous sibling attribute in the DOM. Returns null at beginning.
858
const TiXmlAttribute* Previous() const;
859
TiXmlAttribute* Previous() {
860
return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Previous() );
863
bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; }
864
bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; }
865
bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; }
867
/* Attribute parsing starts: first letter of the name
868
returns: the next char after the value end quote
870
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
872
// Prints this Attribute to a FILE stream.
873
virtual void Print( FILE* cfile, int depth ) const {
874
Print( cfile, depth, 0 );
876
void Print( FILE* cfile, int depth, TIXML_STRING* str ) const;
879
// Set the document pointer so the attribute can report errors.
880
void SetDocument( TiXmlDocument* doc ) { document = doc; }
883
TiXmlAttribute( const TiXmlAttribute& ); // not implemented.
884
void operator=( const TiXmlAttribute& base ); // not allowed.
886
TiXmlDocument* document; // A pointer back to a document, for error reporting.
889
TiXmlAttribute* prev;
890
TiXmlAttribute* next;
894
/* A class used to manage a group of attributes.
895
It is only used internally, both by the ELEMENT and the DECLARATION.
897
The set can be changed transparent to the Element and Declaration
898
classes that use it, but NOT transparent to the Attribute
899
which has to implement a next() and previous() method. Which makes
900
it a bit problematic and prevents the use of STL.
902
This version is implemented with circular lists because:
903
- I like circular lists
904
- it demonstrates some independence from the (typical) doubly linked list.
906
class TiXmlAttributeSet
910
~TiXmlAttributeSet();
912
void Add( TiXmlAttribute* attribute );
913
void Remove( TiXmlAttribute* attribute );
915
const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
916
TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
917
const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
918
TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
920
const TiXmlAttribute* Find( const char* _name ) const;
921
TiXmlAttribute* Find( const char* _name ) {
922
return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttributeSet* >(this))->Find( _name ) );
925
const TiXmlAttribute* Find( const std::string& _name ) const;
926
TiXmlAttribute* Find( const std::string& _name ) {
927
return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttributeSet* >(this))->Find( _name ) );
933
//*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element),
934
//*ME: this class must be also use a hidden/disabled copy-constructor !!!
935
TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed
936
void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute)
938
TiXmlAttribute sentinel;
942
/** The element is a container class. It has a value, the element name,
943
and can contain other elements, text, comments, and unknowns.
944
Elements also contain an arbitrary number of attributes.
946
class TiXmlElement : public TiXmlNode
949
/// Construct an element.
950
TiXmlElement (const char * in_value);
953
/// std::string constructor.
954
TiXmlElement( const std::string& _value );
957
TiXmlElement( const TiXmlElement& );
959
void operator=( const TiXmlElement& base );
961
virtual ~TiXmlElement();
963
/** Given an attribute name, Attribute() returns the value
964
for the attribute of that name, or null if none exists.
966
const char* Attribute( const char* name ) const;
968
/** Given an attribute name, Attribute() returns the value
969
for the attribute of that name, or null if none exists.
970
If the attribute exists and can be converted to an integer,
971
the integer value will be put in the return 'i', if 'i'
974
const char* Attribute( const char* name, int* i ) const;
976
/** Given an attribute name, Attribute() returns the value
977
for the attribute of that name, or null if none exists.
978
If the attribute exists and can be converted to an double,
979
the double value will be put in the return 'd', if 'd'
982
const char* Attribute( const char* name, double* d ) const;
984
/** QueryIntAttribute examines the attribute - it is an alternative to the
985
Attribute() method with richer error checking.
986
If the attribute is an integer, it is stored in 'value' and
987
the call returns TIXML_SUCCESS. If it is not
988
an integer, it returns TIXML_WRONG_TYPE. If the attribute
989
does not exist, then TIXML_NO_ATTRIBUTE is returned.
991
int QueryIntAttribute( const char* name, int* _value ) const;
992
/// QueryDoubleAttribute examines the attribute - see QueryIntAttribute().
993
int QueryDoubleAttribute( const char* name, double* _value ) const;
994
/// QueryFloatAttribute examines the attribute - see QueryIntAttribute().
995
int QueryFloatAttribute( const char* name, float* _value ) const {
997
int result = QueryDoubleAttribute( name, &d );
998
if ( result == TIXML_SUCCESS ) {
1004
#ifdef TIXML_USE_STL
1005
/** Template form of the attribute query which will try to read the
1006
attribute into the specified type. Very easy, very powerful, but
1007
be careful to make sure to call this with the correct type.
1009
NOTE: This method doesn't work correctly for 'string' types.
1011
@return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE
1013
template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const
1015
const TiXmlAttribute* node = attributeSet.Find( name );
1017
return TIXML_NO_ATTRIBUTE;
1019
std::stringstream sstream( node->ValueStr() );
1020
sstream >> *outValue;
1021
if ( !sstream.fail() )
1022
return TIXML_SUCCESS;
1023
return TIXML_WRONG_TYPE;
1026
This is - in theory - a bug fix for "QueryValueAtribute returns truncated std::string"
1027
but template specialization is hard to get working cross-compiler. Leaving the bug for now.
1029
// The above will fail for std::string because the space character is used as a seperator.
1030
// Specialize for strings. Bug [ 1695429 ] QueryValueAtribute returns truncated std::string
1031
template<> int QueryValueAttribute( const std::string& name, std::string* outValue ) const
1033
const TiXmlAttribute* node = attributeSet.Find( name );
1035
return TIXML_NO_ATTRIBUTE;
1036
*outValue = node->ValueStr();
1037
return TIXML_SUCCESS;
1042
/** Sets an attribute of name to a given value. The attribute
1043
will be created if it does not exist, or changed if it does.
1045
void SetAttribute( const char* name, const char * _value );
1047
#ifdef TIXML_USE_STL
1048
const std::string* Attribute( const std::string& name ) const;
1049
const std::string* Attribute( const std::string& name, int* i ) const;
1050
const std::string* Attribute( const std::string& name, double* d ) const;
1051
int QueryIntAttribute( const std::string& name, int* _value ) const;
1052
int QueryDoubleAttribute( const std::string& name, double* _value ) const;
1054
/// STL std::string form.
1055
void SetAttribute( const std::string& name, const std::string& _value );
1056
///< STL std::string form.
1057
void SetAttribute( const std::string& name, int _value );
1060
/** Sets an attribute of name to a given value. The attribute
1061
will be created if it does not exist, or changed if it does.
1063
void SetAttribute( const char * name, int value );
1065
/** Sets an attribute of name to a given value. The attribute
1066
will be created if it does not exist, or changed if it does.
1068
void SetDoubleAttribute( const char * name, double value );
1070
/** Deletes an attribute with the given name.
1072
void RemoveAttribute( const char * name );
1073
#ifdef TIXML_USE_STL
1074
void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form.
1077
const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element.
1078
TiXmlAttribute* FirstAttribute() { return attributeSet.First(); }
1079
const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element.
1080
TiXmlAttribute* LastAttribute() { return attributeSet.Last(); }
1082
/** Convenience function for easy access to the text inside an element. Although easy
1083
and concise, GetText() is limited compared to getting the TiXmlText child
1084
and accessing it directly.
1086
If the first child of 'this' is a TiXmlText, the GetText()
1087
returns the character string of the Text node, else null is returned.
1089
This is a convenient method for getting the text of simple contained text:
1091
<foo>This is text</foo>
1092
const char* str = fooElement->GetText();
1095
'str' will be a pointer to "This is text".
1097
Note that this function can be misleading. If the element foo was created from
1100
<foo><b>This is text</b></foo>
1103
then the value of str would be null. The first child node isn't a text node, it is
1104
another element. From this XML:
1106
<foo>This is <b>text</b></foo>
1108
GetText() will return "This is ".
1110
WARNING: GetText() accesses a child node - don't become confused with the
1111
similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are
1112
safe type casts on the referenced node.
1114
const char* GetText() const;
1116
/// Creates a new Element and returns it - the returned element is a copy.
1117
virtual TiXmlNode* Clone() const;
1118
// Print the Element to a FILE stream.
1119
virtual void Print( FILE* cfile, int depth ) const;
1121
/* Attribtue parsing starts: next char past '<'
1122
returns: next char past '>'
1124
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
1126
virtual const TiXmlElement* ToElement() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1127
virtual TiXmlElement* ToElement() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1129
/** Walk the XML tree visiting this node and all of its children.
1131
virtual bool Accept( TiXmlVisitor* visitor ) const;
1135
void CopyTo( TiXmlElement* target ) const;
1136
void ClearThis(); // like clear, but initializes 'this' object as well
1138
// Used to be public [internal use]
1139
#ifdef TIXML_USE_STL
1140
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
1143
Reads the "value" of the element -- another element, or text.
1144
This should terminate with the current end tag.
1146
const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding );
1150
TiXmlAttributeSet attributeSet;
1156
class TiXmlComment : public TiXmlNode
1159
/// Constructs an empty comment.
1160
TiXmlComment() : TiXmlNode( TiXmlNode::COMMENT ) {}
1161
/// Construct a comment from text.
1162
TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::COMMENT ) {
1165
TiXmlComment( const TiXmlComment& );
1166
void operator=( const TiXmlComment& base );
1168
virtual ~TiXmlComment() {}
1170
/// Returns a copy of this Comment.
1171
virtual TiXmlNode* Clone() const;
1172
// Write this Comment to a FILE stream.
1173
virtual void Print( FILE* cfile, int depth ) const;
1175
/* Attribtue parsing starts: at the ! of the !--
1176
returns: next char past '>'
1178
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
1180
virtual const TiXmlComment* ToComment() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1181
virtual TiXmlComment* ToComment() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1183
/** Walk the XML tree visiting this node and all of its children.
1185
virtual bool Accept( TiXmlVisitor* visitor ) const;
1188
void CopyTo( TiXmlComment* target ) const;
1190
// used to be public
1191
#ifdef TIXML_USE_STL
1192
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
1194
// virtual void StreamOut( TIXML_OSTREAM * out ) const;
1201
/** XML text. A text node can have 2 ways to output the next. "normal" output
1202
and CDATA. It will default to the mode it was parsed from the XML file and
1203
you generally want to leave it alone, but you can change the output mode with
1204
SetCDATA() and query it with CDATA().
1206
class TiXmlText : public TiXmlNode
1208
friend class TiXmlElement;
1210
/** Constructor for text element. By default, it is treated as
1211
normal, encoded text. If you want it be output as a CDATA text
1212
element, set the parameter _cdata to 'true'
1214
TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TEXT)
1216
SetValue( initValue );
1219
virtual ~TiXmlText() {}
1221
#ifdef TIXML_USE_STL
1223
TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TEXT)
1225
SetValue( initValue );
1230
TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TEXT ) { copy.CopyTo( this ); }
1231
void operator=( const TiXmlText& base ) { base.CopyTo( this ); }
1233
// Write this text object to a FILE stream.
1234
virtual void Print( FILE* cfile, int depth ) const;
1236
/// Queries whether this represents text using a CDATA section.
1237
bool CDATA() const { return cdata; }
1238
/// Turns on or off a CDATA representation of text.
1239
void SetCDATA( bool _cdata ) { cdata = _cdata; }
1241
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
1243
virtual const TiXmlText* ToText() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1244
virtual TiXmlText* ToText() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1246
/** Walk the XML tree visiting this node and all of its children.
1248
virtual bool Accept( TiXmlVisitor* content ) const;
1251
/// [internal use] Creates a new Element and returns it.
1252
virtual TiXmlNode* Clone() const;
1253
void CopyTo( TiXmlText* target ) const;
1255
bool Blank() const; // returns true if all white space and new lines
1257
#ifdef TIXML_USE_STL
1258
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
1262
bool cdata; // true if this should be input and output as a CDATA style text element
1266
/** In correct XML the declaration is the first entry in the file.
1268
<?xml version="1.0" standalone="yes"?>
1271
TinyXml will happily read or write files without a declaration,
1272
however. There are 3 possible attributes to the declaration:
1273
version, encoding, and standalone.
1275
Note: In this version of the code, the attributes are
1276
handled as special cases, not generic attributes, simply
1277
because there can only be at most 3 and they are always the same.
1279
class TiXmlDeclaration : public TiXmlNode
1282
/// Construct an empty declaration.
1283
TiXmlDeclaration() : TiXmlNode( TiXmlNode::DECLARATION ) {}
1285
#ifdef TIXML_USE_STL
1287
TiXmlDeclaration( const std::string& _version,
1288
const std::string& _encoding,
1289
const std::string& _standalone );
1293
TiXmlDeclaration( const char* _version,
1294
const char* _encoding,
1295
const char* _standalone );
1297
TiXmlDeclaration( const TiXmlDeclaration& copy );
1298
void operator=( const TiXmlDeclaration& copy );
1300
virtual ~TiXmlDeclaration() {}
1302
/// Version. Will return an empty string if none was found.
1303
const char *Version() const { return version.c_str (); }
1304
/// Encoding. Will return an empty string if none was found.
1305
const char *Encoding() const { return encoding.c_str (); }
1306
/// Is this a standalone document?
1307
const char *Standalone() const { return standalone.c_str (); }
1309
/// Creates a copy of this Declaration and returns it.
1310
virtual TiXmlNode* Clone() const;
1311
// Print this declaration to a FILE stream.
1312
virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const;
1313
virtual void Print( FILE* cfile, int depth ) const {
1314
Print( cfile, depth, 0 );
1317
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
1319
virtual const TiXmlDeclaration* ToDeclaration() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1320
virtual TiXmlDeclaration* ToDeclaration() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1322
/** Walk the XML tree visiting this node and all of its children.
1324
virtual bool Accept( TiXmlVisitor* visitor ) const;
1327
void CopyTo( TiXmlDeclaration* target ) const;
1328
// used to be public
1329
#ifdef TIXML_USE_STL
1330
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
1335
TIXML_STRING version;
1336
TIXML_STRING encoding;
1337
TIXML_STRING standalone;
1341
/** Any tag that tinyXml doesn't recognize is saved as an
1342
unknown. It is a tag of text, but should not be modified.
1343
It will be written back to the XML, unchanged, when the file
1346
DTD tags get thrown into TiXmlUnknowns.
1348
class TiXmlUnknown : public TiXmlNode
1351
TiXmlUnknown() : TiXmlNode( TiXmlNode::UNKNOWN ) {}
1352
virtual ~TiXmlUnknown() {}
1354
TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::UNKNOWN ) { copy.CopyTo( this ); }
1355
void operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); }
1357
/// Creates a copy of this Unknown and returns it.
1358
virtual TiXmlNode* Clone() const;
1359
// Print this Unknown to a FILE stream.
1360
virtual void Print( FILE* cfile, int depth ) const;
1362
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
1364
virtual const TiXmlUnknown* ToUnknown() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1365
virtual TiXmlUnknown* ToUnknown() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1367
/** Walk the XML tree visiting this node and all of its children.
1369
virtual bool Accept( TiXmlVisitor* content ) const;
1372
void CopyTo( TiXmlUnknown* target ) const;
1374
#ifdef TIXML_USE_STL
1375
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
1383
/** Always the top level node. A document binds together all the
1384
XML pieces. It can be saved, loaded, and printed to the screen.
1385
The 'value' of a document node is the xml file name.
1387
class TiXmlDocument : public TiXmlNode
1390
/// Create an empty document, that has no name.
1392
/// Create a document with a name. The name of the document is also the filename of the xml.
1393
TiXmlDocument( const char * documentName );
1395
#ifdef TIXML_USE_STL
1397
TiXmlDocument( const std::string& documentName );
1400
TiXmlDocument( const TiXmlDocument& copy );
1401
void operator=( const TiXmlDocument& copy );
1403
virtual ~TiXmlDocument() {}
1405
/** Load a file using the current document value.
1406
Returns true if successful. Will delete any existing
1407
document data before loading.
1409
bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
1410
/// Save a file using the current document value. Returns true if successful.
1411
bool SaveFile() const;
1412
/// Load a file using the given filename. Returns true if successful.
1413
bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
1414
/// Save a file using the given filename. Returns true if successful.
1415
bool SaveFile( const char * filename ) const;
1416
/** Load a file using the given FILE*. Returns true if successful. Note that this method
1417
doesn't stream - the entire object pointed at by the FILE*
1418
will be interpreted as an XML file. TinyXML doesn't stream in XML from the current
1419
file location. Streaming may be added in the future.
1421
bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
1422
/// Save a file using the given FILE*. Returns true if successful.
1423
bool SaveFile( FILE* ) const;
1425
#ifdef TIXML_USE_STL
1426
bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version.
1428
// StringToBuffer f( filename );
1429
// return ( f.buffer && LoadFile( f.buffer, encoding ));
1430
return LoadFile( filename.c_str(), encoding );
1432
bool SaveFile( const std::string& filename ) const ///< STL std::string version.
1434
// StringToBuffer f( filename );
1435
// return ( f.buffer && SaveFile( f.buffer ));
1436
return SaveFile( filename.c_str() );
1440
/** Parse the given null terminated block of xml data. Passing in an encoding to this
1441
method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml
1442
to use that encoding, regardless of what TinyXml might otherwise try to detect.
1444
virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
1446
/** Get the root element -- the only top level element -- of the document.
1447
In well formed XML, there should only be one. TinyXml is tolerant of
1448
multiple elements at the document level.
1450
const TiXmlElement* RootElement() const { return FirstChildElement(); }
1451
TiXmlElement* RootElement() { return FirstChildElement(); }
1453
/** If an error occurs, Error will be set to true. Also,
1454
- The ErrorId() will contain the integer identifier of the error (not generally useful)
1455
- The ErrorDesc() method will return the name of the error. (very useful)
1456
- The ErrorRow() and ErrorCol() will return the location of the error (if known)
1458
bool Error() const { return error; }
1460
/// Contains a textual (english) description of the error if one occurs.
1461
const char * ErrorDesc() const { return errorDesc.c_str (); }
1463
/** Generally, you probably want the error string ( ErrorDesc() ). But if you
1464
prefer the ErrorId, this function will fetch it.
1466
int ErrorId() const { return errorId; }
1468
/** Returns the location (if known) of the error. The first column is column 1,
1469
and the first row is row 1. A value of 0 means the row and column wasn't applicable
1470
(memory errors, for example, have no row/column) or the parser lost the error. (An
1471
error in the error reporting, in that case.)
1473
@sa SetTabSize, Row, Column
1475
int ErrorRow() const { return errorLocation.row+1; }
1476
int ErrorCol() const { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow()
1478
/** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol())
1479
to report the correct values for row and column. It does not change the output
1480
or input in any way.
1482
By calling this method, with a tab size
1483
greater than 0, the row and column of each node and attribute is stored
1484
when the file is loaded. Very useful for tracking the DOM back in to
1487
The tab size is required for calculating the location of nodes. If not
1488
set, the default of 4 is used. The tabsize is set per document. Setting
1489
the tabsize to 0 disables row/column tracking.
1491
Note that row and column tracking is not supported when using operator>>.
1493
The tab size needs to be enabled before the parse or load. Correct usage:
1496
doc.SetTabSize( 8 );
1497
doc.Load( "myfile.xml" );
1502
void SetTabSize( int _tabsize ) { tabsize = _tabsize; }
1504
int TabSize() const { return tabsize; }
1506
/** If you have handled the error, it can be reset with this call. The error
1507
state is automatically cleared if you Parse a new XML block.
1509
void ClearError() { error = false;
1512
errorLocation.row = errorLocation.col = 0;
1513
//errorLocation.last = 0;
1516
/** Write the document to standard out using formatted printing ("pretty print"). */
1517
void Print() const { Print( stdout, 0 ); }
1519
/* Write the document to a string using formatted printing ("pretty print"). This
1520
will allocate a character array (new char[]) and return it as a pointer. The
1521
calling code pust call delete[] on the return char* to avoid a memory leak.
1523
//char* PrintToMemory() const;
1525
/// Print this Document to a FILE stream.
1526
virtual void Print( FILE* cfile, int depth = 0 ) const;
1528
void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding );
1530
virtual const TiXmlDocument* ToDocument() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1531
virtual TiXmlDocument* ToDocument() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
1533
/** Walk the XML tree visiting this node and all of its children.
1535
virtual bool Accept( TiXmlVisitor* content ) const;
1539
virtual TiXmlNode* Clone() const;
1540
#ifdef TIXML_USE_STL
1541
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
1545
void CopyTo( TiXmlDocument* target ) const;
1549
TIXML_STRING errorDesc;
1551
TiXmlCursor errorLocation;
1552
bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write.
1557
A TiXmlHandle is a class that wraps a node pointer with null checks; this is
1558
an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml
1559
DOM structure. It is a separate utility class.
1564
<Element attributeA = "valueA">
1565
<Child attributeB = "value1" />
1566
<Child attributeB = "value2" />
1571
Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
1572
easy to write a *lot* of code that looks like:
1575
TiXmlElement* root = document.FirstChildElement( "Document" );
1578
TiXmlElement* element = root->FirstChildElement( "Element" );
1581
TiXmlElement* child = element->FirstChildElement( "Child" );
1584
TiXmlElement* child2 = child->NextSiblingElement( "Child" );
1587
// Finally do something useful.
1590
And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity
1591
of such code. A TiXmlHandle checks for null pointers so it is perfectly safe
1595
TiXmlHandle docHandle( &document );
1596
TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).ToElement();
1599
// do something useful
1602
Which is MUCH more concise and useful.
1604
It is also safe to copy handles - internally they are nothing more than node pointers.
1606
TiXmlHandle handleCopy = handle;
1609
What they should not be used for is iteration:
1615
TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).ToElement();
1623
It seems reasonable, but it is in fact two embedded while loops. The Child method is
1624
a linear walk to find the element, so this code would iterate much more than it needs
1625
to. Instead, prefer:
1628
TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).ToElement();
1630
for( child; child; child=child->NextSiblingElement() )
1639
/// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
1640
TiXmlHandle( TiXmlNode* _node ) { this->node = _node; }
1641
/// Copy constructor
1642
TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; }
1643
TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; }
1645
/// Return a handle to the first child node.
1646
TiXmlHandle FirstChild() const;
1647
/// Return a handle to the first child node with the given name.
1648
TiXmlHandle FirstChild( const char * value ) const;
1649
/// Return a handle to the first child element.
1650
TiXmlHandle FirstChildElement() const;
1651
/// Return a handle to the first child element with the given name.
1652
TiXmlHandle FirstChildElement( const char * value ) const;
1654
/** Return a handle to the "index" child with the given name.
1655
The first child is 0, the second 1, etc.
1657
TiXmlHandle Child( const char* value, int index ) const;
1658
/** Return a handle to the "index" child.
1659
The first child is 0, the second 1, etc.
1661
TiXmlHandle Child( int index ) const;
1662
/** Return a handle to the "index" child element with the given name.
1663
The first child element is 0, the second 1, etc. Note that only TiXmlElements
1664
are indexed: other types are not counted.
1666
TiXmlHandle ChildElement( const char* value, int index ) const;
1667
/** Return a handle to the "index" child element.
1668
The first child element is 0, the second 1, etc. Note that only TiXmlElements
1669
are indexed: other types are not counted.
1671
TiXmlHandle ChildElement( int index ) const;
1673
#ifdef TIXML_USE_STL
1674
TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); }
1675
TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); }
1677
TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); }
1678
TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); }
1681
/** Return the handle as a TiXmlNode. This may return null.
1683
TiXmlNode* ToNode() const { return node; }
1684
/** Return the handle as a TiXmlElement. This may return null.
1686
TiXmlElement* ToElement() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); }
1687
/** Return the handle as a TiXmlText. This may return null.
1689
TiXmlText* ToText() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); }
1690
/** Return the handle as a TiXmlUnknown. This may return null.
1692
TiXmlUnknown* ToUnknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); }
1694
/** @deprecated use ToNode.
1695
Return the handle as a TiXmlNode. This may return null.
1697
TiXmlNode* Node() const { return ToNode(); }
1698
/** @deprecated use ToElement.
1699
Return the handle as a TiXmlElement. This may return null.
1701
TiXmlElement* Element() const { return ToElement(); }
1702
/** @deprecated use ToText()
1703
Return the handle as a TiXmlText. This may return null.
1705
TiXmlText* Text() const { return ToText(); }
1706
/** @deprecated use ToUnknown()
1707
Return the handle as a TiXmlUnknown. This may return null.
1709
TiXmlUnknown* Unknown() const { return ToUnknown(); }
1716
/** Print to memory functionality. The TiXmlPrinter is useful when you need to:
1718
-# Print to memory (especially in non-STL mode)
1719
-# Control formatting (line endings, etc.)
1721
When constructed, the TiXmlPrinter is in its default "pretty printing" mode.
1722
Before calling Accept() you can call methods to control the printing
1723
of the XML document. After TiXmlNode::Accept() is called, the printed document can
1724
be accessed via the CStr(), Str(), and Size() methods.
1726
TiXmlPrinter uses the Visitor API.
1728
TiXmlPrinter printer;
1729
printer.SetIndent( "\t" );
1731
doc.Accept( &printer );
1732
fprintf( stdout, "%s", printer.CStr() );
1735
class TiXmlPrinter : public TiXmlVisitor
1738
TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ),
1739
buffer(), indent( " " ), lineBreak( "\n" ) {}
1741
virtual bool VisitEnter( const TiXmlDocument& doc );
1742
virtual bool VisitExit( const TiXmlDocument& doc );
1744
virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute );
1745
virtual bool VisitExit( const TiXmlElement& element );
1747
virtual bool Visit( const TiXmlDeclaration& declaration );
1748
virtual bool Visit( const TiXmlText& text );
1749
virtual bool Visit( const TiXmlComment& comment );
1750
virtual bool Visit( const TiXmlUnknown& unknown );
1752
/** Set the indent characters for printing. By default 4 spaces
1753
but tab (\t) is also useful, or null/empty string for no indentation.
1755
void SetIndent( const char* _indent ) { indent = _indent ? _indent : "" ; }
1756
/// Query the indention string.
1757
const char* Indent() { return indent.c_str(); }
1758
/** Set the line breaking string. By default set to newline (\n).
1759
Some operating systems prefer other characters, or can be
1760
set to the null/empty string for no indenation.
1762
void SetLineBreak( const char* _lineBreak ) { lineBreak = _lineBreak ? _lineBreak : ""; }
1763
/// Query the current line breaking string.
1764
const char* LineBreak() { return lineBreak.c_str(); }
1766
/** Switch over to "stream printing" which is the most dense formatting without
1767
linebreaks. Common when the XML is needed for network transmission.
1769
void SetStreamPrinting() { indent = "";
1772
/// Return the result.
1773
const char* CStr() { return buffer.c_str(); }
1774
/// Return the length of the result string.
1775
size_t Size() { return buffer.size(); }
1777
#ifdef TIXML_USE_STL
1778
/// Return the result.
1779
const std::string& Str() { return buffer; }
1784
for( int i=0; i<depth; ++i )
1787
void DoLineBreak() {
1788
buffer += lineBreak;
1792
bool simpleTextPrint;
1793
TIXML_STRING buffer;
1794
TIXML_STRING indent;
1795
TIXML_STRING lineBreak;
1800
#pragma warning( pop )