LLC2_API
xmlParser.h
Go to the documentation of this file.
00001 /****************************************************************************/
00002 /*! \mainpage XMLParser library
00003  * \section intro_sec Introduction
00004  *
00005  * This is a basic XML parser written in ANSI C++ for portability.
00006  * It works by using recursion and a node tree for breaking
00007  * down the elements of an XML document.
00008  *
00009  * @version     V2.43
00010  * @author      Frank Vanden Berghen
00011  *
00012  * Copyright (c) 2002, Business-Insight
00013  * <a href="http://www.Business-Insight.com">Business-Insight</a>
00014  * All rights reserved.
00015  * See the file <a href="../../AFPL-license.txt">AFPL-license.txt</a> about the licensing terms
00016  *
00017  * \section tutorial First Tutorial
00018  * You can follow a simple <a href="../../xmlParser.html">Tutorial</a> to know the basics...
00019  *
00020  * \section usage General usage: How to include the XMLParser library inside your project.
00021  *
00022  * The library is composed of two files: <a href="../../xmlParser.cpp">xmlParser.cpp</a> and
00023  * <a href="../../xmlParser.h">xmlParser.h</a>. These are the ONLY 2 files that you need when
00024  * using the library inside your own projects.
00025  *
00026  * All the functions of the library are documented inside the comments of the file
00027  * <a href="../../xmlParser.h">xmlParser.h</a>. These comments can be transformed in
00028  * full-fledged HTML documentation using the DOXYGEN software: simply type: "doxygen doxy.cfg"
00029  *
00030  * By default, the XMLParser library uses (char*) for string representation.To use the (wchar_t*)
00031  * version of the library, you need to define the "_UNICODE" preprocessor definition variable
00032  * (this is usually done inside your project definition file) (This is done automatically for you
00033  * when using Visual Studio).
00034  *
00035  * \section example Advanced Tutorial and Many Examples of usage.
00036  *
00037  * Some very small introductory examples are described inside the Tutorial file
00038  * <a href="../../xmlParser.html">xmlParser.html</a>
00039  *
00040  * Some additional small examples are also inside the file <a href="../../xmlTest.cpp">xmlTest.cpp</a>
00041  * (for the "char*" version of the library) and inside the file
00042  * <a href="../../xmlTestUnicode.cpp">xmlTestUnicode.cpp</a> (for the "wchar_t*"
00043  * version of the library). If you have a question, please review these additionnal examples
00044  * before sending an e-mail to the author.
00045  *
00046  * To build the examples:
00047  * - linux/unix: type "make"
00048  * - solaris: type "make -f makefile.solaris"
00049  * - windows: Visual Studio: double-click on xmlParser.dsw
00050  *   (under Visual Studio .NET, the .dsp and .dsw files will be automatically converted to .vcproj and .sln files)
00051  *
00052  * In order to build the examples you need some additional files:
00053  * - linux/unix: makefile
00054  * - solaris: makefile.solaris
00055  * - windows: Visual Studio: *.dsp, xmlParser.dsw and also xmlParser.lib and xmlParser.dll
00056  *
00057  * \section debugging Debugging with the XMLParser library
00058  *
00059  * \subsection debugwin Debugging under WINDOWS
00060  *
00061  *      Inside Visual C++, the "debug versions" of the memory allocation functions are
00062  *      very slow: Do not forget to compile in "release mode" to get maximum speed.
00063  *      When I had to debug a software that was using the XMLParser Library, it was usually
00064  *      a nightmare because the library was sooOOOoooo slow in debug mode (because of the
00065  *  slow memory allocations in Debug mode). To solve this
00066  *      problem, during all the debugging session, I am now using a very fast DLL version of the
00067  *      XMLParser Library (the DLL is compiled in release mode). Using the DLL version of
00068  *      the XMLParser Library allows me to have lightening XML parsing speed even in debug!
00069  *      Other than that, the DLL version is useless: In the release version of my tool,
00070  *      I always use the normal, ".cpp"-based, XMLParser Library (I simply include the
00071  * <a href="../../xmlParser.cpp">xmlParser.cpp</a> and
00072  * <a href="../../xmlParser.h">xmlParser.h</a> files into the project).
00073  *
00074  *      The file <a href="../../XMLNodeAutoexp.txt">XMLNodeAutoexp.txt</a> contains some
00075  * "tweaks" that improve substancially the display of the content of the XMLNode objects
00076  * inside the Visual Studio Debugger. Believe me, once you have seen inside the debugger
00077  * the "smooth" display of the XMLNode objects, you cannot live without it anymore!
00078  *
00079  * \subsection debuglinux Debugging under LINUX/UNIX
00080  *
00081  *      The speed of the debug version of the XMLParser library is tolerable so no extra
00082  * work.has been done.
00083  *
00084  ****************************************************************************/
00085 
00086 #ifndef __INCLUDE_XML_NODE__
00087 #define __INCLUDE_XML_NODE__
00088 
00089 #include <stdlib.h>
00090 
00091 #ifdef _UNICODE
00092 // If you comment the next "define" line then the library will never "switch to" _UNICODE (wchar_t*) mode (16/32 bits per characters).
00093 // This is useful when you get error messages like:
00094 //    'XMLNode::openFileHelper' : cannot convert parameter 2 from 'const char [5]' to 'const wchar_t *'
00095 // The _XMLWIDECHAR preprocessor variable force the XMLParser library into either utf16/32-mode (the proprocessor variable
00096 // must be defined) or utf8-mode(the pre-processor variable must be undefined).
00097 #define _XMLWIDECHAR
00098 #endif
00099 
00100 #if defined(WIN32) || defined(UNDER_CE) || defined(_WIN32) || defined(WIN64) || defined(__BORLANDC__)
00101 // comment the next line if you are under windows and the compiler is not Microsoft Visual Studio (6.0 or .NET) or Borland
00102 #define _XMLWINDOWS
00103 #endif
00104 
00105 #ifdef XMLDLLENTRY
00106 #undef XMLDLLENTRY
00107 #endif
00108 #ifdef _USE_XMLPARSER_DLL
00109 #ifdef _DLL_EXPORTS_
00110 #define XMLDLLENTRY __declspec(dllexport)
00111 #else
00112 #define XMLDLLENTRY __declspec(dllimport)
00113 #endif
00114 #else
00115 #define XMLDLLENTRY
00116 #endif
00117 
00118 // uncomment the next line if you want no support for wchar_t* (no need for the <wchar.h> or <tchar.h> libraries anymore to compile)
00119 //#define XML_NO_WIDE_CHAR
00120 
00121 #ifdef XML_NO_WIDE_CHAR
00122 #undef _XMLWINDOWS
00123 #undef _XMLWIDECHAR
00124 #endif
00125 
00126 #ifdef _XMLWINDOWS
00127 #include <tchar.h>
00128 #else
00129 #define XMLDLLENTRY
00130 #ifndef XML_NO_WIDE_CHAR
00131 #include <wchar.h> // to have 'wcsrtombs' for ANSI version
00132                    // to have 'mbsrtowcs' for WIDECHAR version
00133 #endif
00134 #endif
00135 
00136 // Some common types for char set portable code
00137 #ifdef _XMLWIDECHAR
00138     #define _CXML(c) L ## c
00139     #define XMLCSTR const wchar_t *
00140     #define XMLSTR  wchar_t *
00141     #define XMLCHAR wchar_t
00142 #else
00143     #define _CXML(c) c
00144     #define XMLCSTR const char *
00145     #define XMLSTR  char *
00146     #define XMLCHAR char
00147 #endif
00148 #ifndef FALSE
00149     #define FALSE 0
00150 #endif /* FALSE */
00151 #ifndef TRUE
00152     #define TRUE 1
00153 #endif /* TRUE */
00154 
00155 
00156 /// Enumeration for XML parse errors.
00157 typedef enum XMLError
00158 {
00159     eXMLErrorNone = 0,
00160     eXMLErrorMissingEndTag,
00161     eXMLErrorNoXMLTagFound,
00162     eXMLErrorEmpty,
00163     eXMLErrorMissingTagName,
00164     eXMLErrorMissingEndTagName,
00165     eXMLErrorUnmatchedEndTag,
00166     eXMLErrorUnmatchedEndClearTag,
00167     eXMLErrorUnexpectedToken,
00168     eXMLErrorNoElements,
00169     eXMLErrorFileNotFound,
00170     eXMLErrorFirstTagNotFound,
00171     eXMLErrorUnknownCharacterEntity,
00172     eXMLErrorCharacterCodeAbove255,
00173     eXMLErrorCharConversionError,
00174     eXMLErrorCannotOpenWriteFile,
00175     eXMLErrorCannotWriteFile,
00176 
00177     eXMLErrorBase64DataSizeIsNotMultipleOf4,
00178     eXMLErrorBase64DecodeIllegalCharacter,
00179     eXMLErrorBase64DecodeTruncatedData,
00180     eXMLErrorBase64DecodeBufferTooSmall
00181 } XMLError;
00182 
00183 
00184 /// Enumeration used to manage type of data. Use in conjunction with structure XMLNodeContents
00185 typedef enum XMLElementType
00186 {
00187     eNodeChild=0,
00188     eNodeAttribute=1,
00189     eNodeText=2,
00190     eNodeClear=3,
00191     eNodeNULL=4
00192 } XMLElementType;
00193 
00194 /// Structure used to obtain error details if the parse fails.
00195 typedef struct XMLResults
00196 {
00197     enum XMLError error;
00198     int  nLine,nColumn;
00199 } XMLResults;
00200 
00201 /// Structure for XML clear (unformatted) node (usually comments)
00202 typedef struct XMLClear {
00203     XMLCSTR lpszValue; XMLCSTR lpszOpenTag; XMLCSTR lpszCloseTag;
00204 } XMLClear;
00205 
00206 /// Structure for XML attribute.
00207 typedef struct XMLAttribute {
00208     XMLCSTR lpszName; XMLCSTR lpszValue;
00209 } XMLAttribute;
00210 
00211 /// XMLElementPosition are not interchangeable with simple indexes
00212 typedef int XMLElementPosition;
00213 
00214 struct XMLNodeContents;
00215 
00216 /** @defgroup XMLParserGeneral The XML parser */
00217 
00218 /// Main Class representing a XML node
00219 /**
00220  * All operations are performed using this class.
00221  * \note The constructors of the XMLNode class are protected, so use instead one of these four methods to get your first instance of XMLNode:
00222  * <ul>
00223  *    <li> XMLNode::parseString </li>
00224  *    <li> XMLNode::parseFile </li>
00225  *    <li> XMLNode::openFileHelper </li>
00226  *    <li> XMLNode::createXMLTopNode (or XMLNode::createXMLTopNode_WOSD)</li>
00227  * </ul> */
00228 typedef struct XMLDLLENTRY XMLNode
00229 {
00230   private:
00231 
00232     struct XMLNodeDataTag;
00233 
00234     /// Constructors are protected, so use instead one of: XMLNode::parseString, XMLNode::parseFile, XMLNode::openFileHelper, XMLNode::createXMLTopNode
00235     XMLNode(struct XMLNodeDataTag *pParent, XMLSTR lpszName, char isDeclaration);
00236     /// Constructors are protected, so use instead one of: XMLNode::parseString, XMLNode::parseFile, XMLNode::openFileHelper, XMLNode::createXMLTopNode
00237     XMLNode(struct XMLNodeDataTag *p);
00238 
00239   public:
00240     static XMLCSTR getVersion();///< Return the XMLParser library version number
00241 
00242     /** @defgroup conversions Parsing XML files/strings to an XMLNode structure and Rendering XMLNode's to files/string.
00243      * @ingroup XMLParserGeneral
00244      * @{ */
00245 
00246     /// Parse an XML string and return the root of a XMLNode tree representing the string.
00247     static XMLNode parseString   (XMLCSTR  lpXMLString, XMLCSTR tag=NULL, XMLResults *pResults=NULL);
00248     /**< The "parseString" function parse an XML string and return the root of a XMLNode tree. The "opposite" of this function is
00249      * the function "createXMLString" that re-creates an XML string from an XMLNode tree. If the XML document is corrupted, the
00250      * "parseString" method will initialize the "pResults" variable with some information that can be used to trace the error.
00251      * If you still want to parse the file, you can use the APPROXIMATE_PARSING option as explained inside the note at the
00252      * beginning of the "xmlParser.cpp" file.
00253      *
00254      * @param lpXMLString the XML string to parse
00255      * @param tag  the name of the first tag inside the XML file. If the tag parameter is omitted, this function returns a node that represents the head of the xml document including the declaration term (<? ... ?>).
00256      * @param pResults a pointer to a XMLResults variable that will contain some information that can be used to trace the XML parsing error. You can have a user-friendly explanation of the parsing error with the "getError" function.
00257      */
00258 
00259     /// Parse an XML file and return the root of a XMLNode tree representing the file.
00260     static XMLNode parseFile     (XMLCSTR     filename, XMLCSTR tag=NULL, XMLResults *pResults=NULL);
00261     /**< The "parseFile" function parse an XML file and return the root of a XMLNode tree. The "opposite" of this function is
00262      * the function "writeToFile" that re-creates an XML file from an XMLNode tree. If the XML document is corrupted, the
00263      * "parseFile" method will initialize the "pResults" variable with some information that can be used to trace the error.
00264      * If you still want to parse the file, you can use the APPROXIMATE_PARSING option as explained inside the note at the
00265      * beginning of the "xmlParser.cpp" file.
00266      *
00267      * @param filename the path to the XML file to parse
00268      * @param tag the name of the first tag inside the XML file. If the tag parameter is omitted, this function returns a node that represents the head of the xml document including the declaration term (<? ... ?>).
00269      * @param pResults a pointer to a XMLResults variable that will contain some information that can be used to trace the XML parsing error. You can have a user-friendly explanation of the parsing error with the "getError" function.
00270      */
00271 
00272     /// Parse an XML file and return the root of a XMLNode tree representing the file. A very crude error checking is made. An attempt to guess the Char Encoding used in the file is made.
00273     static XMLNode openFileHelper(XMLCSTR     filename, XMLCSTR tag=NULL);
00274     /**< The "openFileHelper" function reports to the screen all the warnings and errors that occurred during parsing of the XML file.
00275      * This function also tries to guess char Encoding (UTF-8, ASCII or SHIT-JIS) based on the first 200 bytes of the file. Since each
00276      * application has its own way to report and deal with errors, you should rather use the "parseFile" function to parse XML files
00277      * and program yourself thereafter an "error reporting" tailored for your needs (instead of using the very crude "error reporting"
00278      * mechanism included inside the "openFileHelper" function).
00279      *
00280      * If the XML document is corrupted, the "openFileHelper" method will:
00281      *         - display an error message on the console (or inside a messageBox for windows).
00282      *         - stop execution (exit).
00283      *
00284      * I strongly suggest that you write your own "openFileHelper" method tailored to your needs. If you still want to parse
00285      * the file, you can use the APPROXIMATE_PARSING option as explained inside the note at the beginning of the "xmlParser.cpp" file.
00286      *
00287      * @param filename the path of the XML file to parse.
00288      * @param tag the name of the first tag inside the XML file. If the tag parameter is omitted, this function returns a node that represents the head of the xml document including the declaration term (<? ... ?>).
00289      */
00290 
00291     static XMLCSTR getError(XMLError error); ///< this gives you a user-friendly explanation of the parsing error
00292 
00293     /// Create an XML string starting from the current XMLNode.
00294     XMLSTR createXMLString(int nFormat=1, int *pnSize=NULL) const;
00295     /**< The returned string should be free'd using the "freeXMLString" function.
00296      *
00297      *   If nFormat==0, no formatting is required otherwise this returns an user friendly XML string from a given element
00298      *   with appropriate white spaces and carriage returns. if pnSize is given it returns the size in character of the string. */
00299 
00300     /// Save the content of an xmlNode inside a file
00301     XMLError writeToFile(XMLCSTR filename,
00302                          const char *encoding=NULL,
00303                          char nFormat=1) const;
00304     /**< If nFormat==0, no formatting is required otherwise this returns an user friendly XML string from a given element with appropriate white spaces and carriage returns.
00305      * If the global parameter "characterEncoding==encoding_UTF8", then the "encoding" parameter is ignored and always set to "utf-8".
00306      * If the global parameter "characterEncoding==encoding_ShiftJIS", then the "encoding" parameter is ignored and always set to "SHIFT-JIS".
00307      * If "_XMLWIDECHAR=1", then the "encoding" parameter is ignored and always set to "utf-16".
00308      * If no "encoding" parameter is given the "ISO-8859-1" encoding is used. */
00309     /** @} */
00310 
00311     /** @defgroup navigate Navigate the XMLNode structure
00312      * @ingroup XMLParserGeneral
00313      * @{ */
00314     XMLCSTR getName() const;                                       ///< name of the node
00315     XMLCSTR getText(int i=0) const;                                ///< return ith text field
00316     int nText() const;                                             ///< nbr of text field
00317     XMLNode getParentNode() const;                                 ///< return the parent node
00318     XMLNode getChildNode(int i=0) const;                           ///< return ith child node
00319     XMLNode getChildNode(XMLCSTR name, int i)  const;              ///< return ith child node with specific name (return an empty node if failing). If i==-1, this returns the last XMLNode with the given name.
00320     XMLNode getChildNode(XMLCSTR name, int *i=NULL) const;         ///< return next child node with specific name (return an empty node if failing)
00321     XMLNode getChildNodeWithAttribute(XMLCSTR tagName,
00322                                       XMLCSTR attributeName,
00323                                       XMLCSTR attributeValue=NULL,
00324                                       int *i=NULL)  const;         ///< return child node with specific name/attribute (return an empty node if failing)
00325     XMLNode getChildNodeByPath(XMLCSTR path, char createNodeIfMissing=0, XMLCHAR sep='/');
00326                                                                    ///< return the first child node with specific path
00327     XMLNode getChildNodeByPathNonConst(XMLSTR  path, char createNodeIfMissing=0, XMLCHAR sep='/');
00328                                                                    ///< return the first child node with specific path.
00329 
00330     int nChildNode(XMLCSTR name) const;                            ///< return the number of child node with specific name
00331     int nChildNode() const;                                        ///< nbr of child node
00332     XMLAttribute getAttribute(int i=0) const;                      ///< return ith attribute
00333     XMLCSTR      getAttributeName(int i=0) const;                  ///< return ith attribute name
00334     XMLCSTR      getAttributeValue(int i=0) const;                 ///< return ith attribute value
00335     char  isAttributeSet(XMLCSTR name) const;                      ///< test if an attribute with a specific name is given
00336     XMLCSTR getAttribute(XMLCSTR name, int i) const;               ///< return ith attribute content with specific name (return a NULL if failing)
00337     XMLCSTR getAttribute(XMLCSTR name, int *i=NULL) const;         ///< return next attribute content with specific name (return a NULL if failing)
00338     int nAttribute() const;                                        ///< nbr of attribute
00339     XMLClear getClear(int i=0) const;                              ///< return ith clear field (comments)
00340     int nClear() const;                                            ///< nbr of clear field
00341     XMLNodeContents enumContents(XMLElementPosition i) const;      ///< enumerate all the different contents (attribute,child,text, clear) of the current XMLNode. The order is reflecting the order of the original file/string. NOTE: 0 <= i < nElement();
00342     int nElement() const;                                          ///< nbr of different contents for current node
00343     char isEmpty() const;                                          ///< is this node Empty?
00344     char isDeclaration() const;                                    ///< is this node a declaration <? .... ?>
00345     XMLNode deepCopy() const;                                      ///< deep copy (duplicate/clone) a XMLNode
00346     static XMLNode emptyNode();                                    ///< return XMLNode::emptyXMLNode;
00347     /** @} */
00348 
00349     ~XMLNode();
00350     XMLNode(const XMLNode &A);                                     ///< to allow shallow/fast copy:
00351     XMLNode& operator=( const XMLNode& A );                        ///< to allow shallow/fast copy:
00352 
00353     XMLNode(): d(NULL){};
00354     static XMLNode emptyXMLNode;
00355     static XMLClear emptyXMLClear;
00356     static XMLAttribute emptyXMLAttribute;
00357 
00358     /** @defgroup xmlModify Create or Update the XMLNode structure
00359      * @ingroup XMLParserGeneral
00360      *  The functions in this group allows you to create from scratch (or update) a XMLNode structure. Start by creating your top
00361      *  node with the "createXMLTopNode" function and then add new nodes with the "addChild" function. The parameter 'pos' gives
00362      *  the position where the childNode, the text or the XMLClearTag will be inserted. The default value (pos=-1) inserts at the
00363      *  end. The value (pos=0) insert at the beginning (Insertion at the beginning is slower than at the end). <br>
00364      *
00365      *  REMARK: 0 <= pos < nChild()+nText()+nClear() <br>
00366      */
00367 
00368     /** @defgroup creation Creating from scratch a XMLNode structure
00369      * @ingroup xmlModify
00370      * @{ */
00371     static XMLNode createXMLTopNode(XMLCSTR lpszName, char isDeclaration=FALSE);                    ///< Create the top node of an XMLNode structure
00372     XMLNode        addChild(XMLCSTR lpszName, char isDeclaration=FALSE, XMLElementPosition pos=-1); ///< Add a new child node
00373     XMLNode        addChild(XMLNode nodeToAdd, XMLElementPosition pos=-1);                          ///< If the "nodeToAdd" has some parents, it will be detached from it's parents before being attached to the current XMLNode
00374     XMLAttribute  *addAttribute(XMLCSTR lpszName, XMLCSTR lpszValuev);                              ///< Add a new attribute
00375     XMLCSTR        addText(XMLCSTR lpszValue, XMLElementPosition pos=-1);                           ///< Add a new text content
00376     XMLClear      *addClear(XMLCSTR lpszValue, XMLCSTR lpszOpen=NULL, XMLCSTR lpszClose=NULL, XMLElementPosition pos=-1);
00377     /**< Add a new clear tag
00378      * @param lpszOpen default value "<![CDATA["
00379      * @param lpszClose default value "]]>"
00380      */
00381     /** @} */
00382 
00383     /** @defgroup xmlUpdate Updating Nodes
00384      * @ingroup xmlModify
00385      * Some update functions:
00386      * @{
00387      */
00388     XMLCSTR       updateName(XMLCSTR lpszName);                                                  ///< change node's name
00389     XMLAttribute *updateAttribute(XMLAttribute *newAttribute, XMLAttribute *oldAttribute);       ///< if the attribute to update is missing, a new one will be added
00390     XMLAttribute *updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName=NULL,int i=0);       ///< if the attribute to update is missing, a new one will be added
00391     XMLAttribute *updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,XMLCSTR lpszOldName);///< set lpszNewName=NULL if you don't want to change the name of the attribute if the attribute to update is missing, a new one will be added
00392     XMLCSTR       updateText(XMLCSTR lpszNewValue, int i=0);                                     ///< if the text to update is missing, a new one will be added
00393     XMLCSTR       updateText(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue);                        ///< if the text to update is missing, a new one will be added
00394     XMLClear     *updateClear(XMLCSTR lpszNewContent, int i=0);                                  ///< if the clearTag to update is missing, a new one will be added
00395     XMLClear     *updateClear(XMLClear *newP,XMLClear *oldP);                                    ///< if the clearTag to update is missing, a new one will be added
00396     XMLClear     *updateClear(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue);                       ///< if the clearTag to update is missing, a new one will be added
00397     /** @} */
00398 
00399     /** @defgroup xmlDelete Deleting Nodes or Attributes
00400      * @ingroup xmlModify
00401      * Some deletion functions:
00402      * @{
00403      */
00404     /// The "deleteNodeContent" function forces the deletion of the content of this XMLNode and the subtree.
00405     void deleteNodeContent();
00406     /**< \note The XMLNode instances that are referring to the part of the subtree that has been deleted CANNOT be used anymore!!. Unexpected results will occur if you continue using them. */
00407     void deleteAttribute(int i=0);                   ///< Delete the ith attribute of the current XMLNode
00408     void deleteAttribute(XMLCSTR lpszName);          ///< Delete the attribute with the given name (the "strcmp" function is used to find the right attribute)
00409     void deleteAttribute(XMLAttribute *anAttribute); ///< Delete the attribute with the name "anAttribute->lpszName" (the "strcmp" function is used to find the right attribute)
00410     void deleteText(int i=0);                        ///< Delete the Ith text content of the current XMLNode
00411     void deleteText(XMLCSTR lpszValue);              ///< Delete the text content "lpszValue" inside the current XMLNode (direct "pointer-to-pointer" comparison is used to find the right text)
00412     void deleteClear(int i=0);                       ///< Delete the Ith clear tag inside the current XMLNode
00413     void deleteClear(XMLCSTR lpszValue);             ///< Delete the clear tag "lpszValue" inside the current XMLNode (direct "pointer-to-pointer" comparison is used to find the clear tag)
00414     void deleteClear(XMLClear *p);                   ///< Delete the clear tag "p" inside the current XMLNode (direct "pointer-to-pointer" comparison on the lpszName of the clear tag is used to find the clear tag)
00415     /** @} */
00416 
00417     /** @defgroup xmlWOSD ???_WOSD functions.
00418      * @ingroup xmlModify
00419      *  The strings given as parameters for the "add" and "update" methods that have a name with
00420      *  the postfix "_WOSD" (that means "WithOut String Duplication")(for example "addText_WOSD")
00421      *  will be free'd by the XMLNode class. For example, it means that this is incorrect:
00422      *  \code
00423      *     xNode.addText_WOSD("foo");
00424      *     xNode.updateAttribute_WOSD("#newcolor" ,NULL,"color");
00425      *  \endcode
00426      *  In opposition, this is correct:
00427      *  \code
00428      *     xNode.addText("foo");
00429      *     xNode.addText_WOSD(stringDup("foo"));
00430      *     xNode.updateAttribute("#newcolor" ,NULL,"color");
00431      *     xNode.updateAttribute_WOSD(stringDup("#newcolor"),NULL,"color");
00432      *  \endcode
00433      *  Typically, you will never do:
00434      *  \code
00435      *     char *b=(char*)malloc(...);
00436      *     xNode.addText(b);
00437      *     free(b);
00438      *  \endcode
00439      *  ... but rather:
00440      *  \code
00441      *     char *b=(char*)malloc(...);
00442      *     xNode.addText_WOSD(b);
00443      *  \endcode
00444      *  ('free(b)' is performed by the XMLNode class)
00445      * @{ */
00446     static XMLNode createXMLTopNode_WOSD(XMLSTR lpszName, char isDeclaration=FALSE);                     ///< Create the top node of an XMLNode structure
00447     XMLNode        addChild_WOSD(XMLSTR lpszName, char isDeclaration=FALSE, XMLElementPosition pos=-1);  ///< Add a new child node
00448     XMLAttribute  *addAttribute_WOSD(XMLSTR lpszName, XMLSTR lpszValue);                                 ///< Add a new attribute
00449     XMLCSTR        addText_WOSD(XMLSTR lpszValue, XMLElementPosition pos=-1);                            ///< Add a new text content
00450     XMLClear      *addClear_WOSD(XMLSTR lpszValue, XMLCSTR lpszOpen=NULL, XMLCSTR lpszClose=NULL, XMLElementPosition pos=-1); ///< Add a new clear Tag
00451 
00452     XMLCSTR        updateName_WOSD(XMLSTR lpszName);                                                  ///< change node's name
00453     XMLAttribute  *updateAttribute_WOSD(XMLAttribute *newAttribute, XMLAttribute *oldAttribute);      ///< if the attribute to update is missing, a new one will be added
00454     XMLAttribute  *updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName=NULL,int i=0);        ///< if the attribute to update is missing, a new one will be added
00455     XMLAttribute  *updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName,XMLCSTR lpszOldName); ///< set lpszNewName=NULL if you don't want to change the name of the attribute if the attribute to update is missing, a new one will be added
00456     XMLCSTR        updateText_WOSD(XMLSTR lpszNewValue, int i=0);                                     ///< if the text to update is missing, a new one will be added
00457     XMLCSTR        updateText_WOSD(XMLSTR lpszNewValue, XMLCSTR lpszOldValue);                        ///< if the text to update is missing, a new one will be added
00458     XMLClear      *updateClear_WOSD(XMLSTR lpszNewContent, int i=0);                                  ///< if the clearTag to update is missing, a new one will be added
00459     XMLClear      *updateClear_WOSD(XMLClear *newP,XMLClear *oldP);                                   ///< if the clearTag to update is missing, a new one will be added
00460     XMLClear      *updateClear_WOSD(XMLSTR lpszNewValue, XMLCSTR lpszOldValue);                       ///< if the clearTag to update is missing, a new one will be added
00461     /** @} */
00462 
00463     /** @defgroup xmlPosition Position helper functions (use in conjunction with the update&add functions
00464      * @ingroup xmlModify
00465      * These are some useful functions when you want to insert a childNode, a text or a XMLClearTag in the
00466      * middle (at a specified position) of a XMLNode tree already constructed. The value returned by these
00467      * methods is to be used as last parameter (parameter 'pos') of addChild, addText or addClear.
00468      * @{ */
00469     XMLElementPosition positionOfText(int i=0) const;
00470     XMLElementPosition positionOfText(XMLCSTR lpszValue) const;
00471     XMLElementPosition positionOfClear(int i=0) const;
00472     XMLElementPosition positionOfClear(XMLCSTR lpszValue) const;
00473     XMLElementPosition positionOfClear(XMLClear *a) const;
00474     XMLElementPosition positionOfChildNode(int i=0) const;
00475     XMLElementPosition positionOfChildNode(XMLNode x) const;
00476     XMLElementPosition positionOfChildNode(XMLCSTR name, int i=0) const; ///< return the position of the ith childNode with the specified name if (name==NULL) return the position of the ith childNode
00477     /** @} */
00478 
00479     /// Enumeration for XML character encoding.
00480     typedef enum XMLCharEncoding
00481     {
00482         char_encoding_error=0,
00483         char_encoding_UTF8=1,
00484         char_encoding_legacy=2,
00485         char_encoding_ShiftJIS=3,
00486         char_encoding_GB2312=4,
00487         char_encoding_Big5=5,
00488         char_encoding_GBK=6     // this is actually the same as Big5
00489     } XMLCharEncoding;
00490 
00491     /** \addtogroup conversions
00492      * @{ */
00493 
00494     /// Sets the global options for the conversions
00495     static char setGlobalOptions(XMLCharEncoding characterEncoding=XMLNode::char_encoding_UTF8, char guessWideCharChars=1,
00496                                  char dropWhiteSpace=1, char removeCommentsInMiddleOfText=1);
00497     /**< The "setGlobalOptions" function allows you to change four global parameters that affect string & file
00498      * parsing. First of all, you most-probably will never have to change these 3 global parameters.
00499      *
00500      * @param guessWideCharChars If "guessWideCharChars"=1 and if this library is compiled in WideChar mode, then the
00501      *     XMLNode::parseFile and XMLNode::openFileHelper functions will test if the file contains ASCII
00502      *     characters. If this is the case, then the file will be loaded and converted in memory to
00503      *     WideChar before being parsed. If 0, no conversion will be performed.
00504      *
00505      * @param guessWideCharChars If "guessWideCharChars"=1 and if this library is compiled in ASCII/UTF8/char* mode, then the
00506      *     XMLNode::parseFile and XMLNode::openFileHelper functions will test if the file contains WideChar
00507      *     characters. If this is the case, then the file will be loaded and converted in memory to
00508      *     ASCII/UTF8/char* before being parsed. If 0, no conversion will be performed.
00509      *
00510      * @param characterEncoding This parameter is only meaningful when compiling in char* mode (multibyte character mode).
00511      *     In wchar_t* (wide char mode), this parameter is ignored. This parameter should be one of the
00512      *     three currently recognized encodings: XMLNode::encoding_UTF8, XMLNode::encoding_ascii,
00513      *     XMLNode::encoding_ShiftJIS.
00514      *
00515      * @param dropWhiteSpace In most situations, text fields containing only white spaces (and carriage returns)
00516      *     are useless. Even more, these "empty" text fields are annoying because they increase the
00517      *     complexity of the user's code for parsing. So, 99% of the time, it's better to drop
00518      *     the "empty" text fields. However The XML specification indicates that no white spaces
00519      *     should be lost when parsing the file. So to be perfectly XML-compliant, you should set
00520      *     dropWhiteSpace=0. A note of caution: if you set "dropWhiteSpace=0", the parser will be
00521      *     slower and your code will be more complex.
00522      *
00523      * @param removeCommentsInMiddleOfText To explain this parameter, let's consider this code:
00524      * \code
00525      *        XMLNode x=XMLNode::parseString("<a>foo<!-- hello -->bar<!DOCTYPE world >chu</a>","a");
00526      * \endcode
00527      *     If removeCommentsInMiddleOfText=0, then we will have:
00528      * \code
00529      *        x.getText(0) -> "foo"
00530      *        x.getText(1) -> "bar"
00531      *        x.getText(2) -> "chu"
00532      *        x.getClear(0) --> "<!-- hello -->"
00533      *        x.getClear(1) --> "<!DOCTYPE world >"
00534      * \endcode
00535      *     If removeCommentsInMiddleOfText=1, then we will have:
00536      * \code
00537      *        x.getText(0) -> "foobar"
00538      *        x.getText(1) -> "chu"
00539      *        x.getClear(0) --> "<!DOCTYPE world >"
00540      * \endcode
00541      *
00542      * \return "0" when there are no errors. If you try to set an unrecognized encoding then the return value will be "1" to signal an error.
00543      *
00544      * \note Sometime, it's useful to set "guessWideCharChars=0" to disable any conversion
00545      * because the test to detect the file-type (ASCII/UTF8/char* or WideChar) may fail (rarely). */
00546 
00547     /// Guess the character encoding of the string (ascii, utf8 or shift-JIS)
00548     static XMLCharEncoding guessCharEncoding(void *buffer, int bufLen, char useXMLEncodingAttribute=1);
00549     /**< The "guessCharEncoding" function try to guess the character encoding. You most-probably will never
00550      * have to use this function. It then returns the appropriate value of the global parameter
00551      * "characterEncoding" described in the XMLNode::setGlobalOptions. The guess is based on the content of a buffer of length
00552      * "bufLen" bytes that contains the first bytes (minimum 25 bytes; 200 bytes is a good value) of the
00553      * file to be parsed. The XMLNode::openFileHelper function is using this function to automatically compute
00554      * the value of the "characterEncoding" global parameter. There are several heuristics used to do the
00555      * guess. One of the heuristic is based on the "encoding" attribute. The original XML specifications
00556      * forbids to use this attribute to do the guess but you can still use it if you set
00557      * "useXMLEncodingAttribute" to 1 (this is the default behavior and the behavior of most parsers).
00558      * If an inconsistency in the encoding is detected, then the return value is "0". */
00559     /** @} */
00560 
00561   private:
00562       // these are functions and structures used internally by the XMLNode class (don't bother about them):
00563 
00564       typedef struct XMLNodeDataTag // to allow shallow copy and "intelligent/smart" pointers (automatic delete):
00565       {
00566           XMLCSTR                lpszName;        // Element name (=NULL if root)
00567           int                    nChild,          // Number of child nodes
00568                                  nText,           // Number of text fields
00569                                  nClear,          // Number of Clear fields (comments)
00570                                  nAttribute;      // Number of attributes
00571           char                   isDeclaration;   // Whether node is an XML declaration - '<?xml ?>'
00572           struct XMLNodeDataTag  *pParent;        // Pointer to parent element (=NULL if root)
00573           XMLNode                *pChild;         // Array of child nodes
00574           XMLCSTR                *pText;          // Array of text fields
00575           XMLClear               *pClear;         // Array of clear fields
00576           XMLAttribute           *pAttribute;     // Array of attributes
00577           int                    *pOrder;         // order of the child_nodes,text_fields,clear_fields
00578           int                    ref_count;       // for garbage collection (smart pointers)
00579       } XMLNodeData;
00580       XMLNodeData *d;
00581 
00582       char parseClearTag(void *px, void *pa);
00583       char maybeAddTxT(void *pa, XMLCSTR tokenPStr);
00584       int ParseXMLElement(void *pXML);
00585       void *addToOrder(int memInc, int *_pos, int nc, void *p, int size, XMLElementType xtype);
00586       int indexText(XMLCSTR lpszValue) const;
00587       int indexClear(XMLCSTR lpszValue) const;
00588       XMLNode addChild_priv(int,XMLSTR,char,int);
00589       XMLAttribute *addAttribute_priv(int,XMLSTR,XMLSTR);
00590       XMLCSTR addText_priv(int,XMLSTR,int);
00591       XMLClear *addClear_priv(int,XMLSTR,XMLCSTR,XMLCSTR,int);
00592       void emptyTheNode(char force);
00593       static inline XMLElementPosition findPosition(XMLNodeData *d, int index, XMLElementType xtype);
00594       static int CreateXMLStringR(XMLNodeData *pEntry, XMLSTR lpszMarker, int nFormat);
00595       static int removeOrderElement(XMLNodeData *d, XMLElementType t, int index);
00596       static void exactMemory(XMLNodeData *d);
00597       static int detachFromParent(XMLNodeData *d);
00598 } XMLNode;
00599 
00600 /// This structure is given by the function XMLNode::enumContents.
00601 typedef struct XMLNodeContents
00602 {
00603     /// This dictates what's the content of the XMLNodeContent
00604     enum XMLElementType etype;
00605     /**< should be an union to access the appropriate data. Compiler does not allow union of object with constructor... too bad. */
00606     XMLNode child;
00607     XMLAttribute attrib;
00608     XMLCSTR text;
00609     XMLClear clear;
00610 
00611 } XMLNodeContents;
00612 
00613 /** @defgroup StringAlloc String Allocation/Free functions
00614  * @ingroup xmlModify
00615  * @{ */
00616 /// Duplicate (copy in a new allocated buffer) the source string.
00617 XMLDLLENTRY XMLSTR stringDup(XMLCSTR source, int cbData=-1);
00618 /**< This is
00619  * a very handy function when used with all the "XMLNode::*_WOSD" functions (\link xmlWOSD \endlink).
00620  * @param cbData If !=0 then cbData is the number of chars to duplicate. New strings allocated with
00621  * this function should be free'd using the "freeXMLString" function. */
00622 
00623 /// to free the string allocated inside the "stringDup" function or the "createXMLString" function.
00624 XMLDLLENTRY void freeXMLString(XMLSTR t); // {free(t);}
00625 /** @} */
00626 
00627 /** @defgroup atoX ato? like functions
00628  * @ingroup XMLParserGeneral
00629  * The "xmlto?" functions are equivalents to the atoi, atol, atof functions.
00630  * The only difference is: If the variable "xmlString" is NULL, than the return value
00631  * is "defautValue". These 6 functions are only here as "convenience" functions for the
00632  * user (they are not used inside the XMLparser). If you don't need them, you can
00633  * delete them without any trouble.
00634  *
00635  * @{ */
00636 XMLDLLENTRY char    xmltob(XMLCSTR xmlString,char   defautValue=0);
00637 XMLDLLENTRY int     xmltoi(XMLCSTR xmlString,int    defautValue=0);
00638 XMLDLLENTRY long    xmltol(XMLCSTR xmlString,long   defautValue=0);
00639 XMLDLLENTRY double  xmltof(XMLCSTR xmlString,double defautValue=.0);
00640 XMLDLLENTRY XMLCSTR xmltoa(XMLCSTR xmlString,XMLCSTR defautValue=_CXML(""));
00641 XMLDLLENTRY XMLCHAR xmltoc(XMLCSTR xmlString,const XMLCHAR defautValue=_CXML('\0'));
00642 /** @} */
00643 
00644 /** @defgroup ToXMLStringTool Helper class to create XML files using "printf", "fprintf", "cout",... functions.
00645  * @ingroup XMLParserGeneral
00646  * @{ */
00647 /// Helper class to create XML files using "printf", "fprintf", "cout",... functions.
00648 /** The ToXMLStringTool class helps you creating XML files using "printf", "fprintf", "cout",... functions.
00649  * The "ToXMLStringTool" class is processing strings so that all the characters
00650  * &,",',<,> are replaced by their XML equivalent:
00651  * \verbatim &amp;, &quot;, &apos;, &lt;, &gt; \endverbatim
00652  * Using the "ToXMLStringTool class" and the "fprintf function" is THE most efficient
00653  * way to produce VERY large XML documents VERY fast.
00654  * \note If you are creating from scratch an XML file using the provided XMLNode class
00655  * you must not use the "ToXMLStringTool" class (because the "XMLNode" class does the
00656  * processing job for you during rendering).*/
00657 typedef struct XMLDLLENTRY ToXMLStringTool
00658 {
00659 public:
00660     ToXMLStringTool(): buf(NULL),buflen(0){}
00661     ~ToXMLStringTool();
00662     void freeBuffer();///<call this function when you have finished using this object to release memory used by the internal buffer.
00663 
00664     XMLSTR toXML(XMLCSTR source);///< returns a pointer to an internal buffer that contains a XML-encoded string based on the "source" parameter.
00665 
00666     /** The "toXMLUnSafe" function is deprecated because there is a possibility of
00667      * "destination-buffer-overflow". It converts the string
00668      * "source" to the string "dest". */
00669     static XMLSTR toXMLUnSafe(XMLSTR dest,XMLCSTR source); ///< deprecated: use "toXML" instead
00670     static int lengthXMLString(XMLCSTR source);            ///< deprecated: use "toXML" instead
00671 
00672 private:
00673     XMLSTR buf;
00674     int buflen;
00675 } ToXMLStringTool;
00676 /** @} */
00677 
00678 /** @defgroup XMLParserBase64Tool Helper class to include binary data inside XML strings using "Base64 encoding".
00679  * @ingroup XMLParserGeneral
00680  * @{ */
00681 /// Helper class to include binary data inside XML strings using "Base64 encoding".
00682 /** The "XMLParserBase64Tool" class allows you to include any binary data (images, sounds,...)
00683  * into an XML document using "Base64 encoding". This class is completely
00684  * separated from the rest of the xmlParser library and can be removed without any problem.
00685  * To include some binary data into an XML file, you must convert the binary data into
00686  * standard text (using "encode"). To retrieve the original binary data from the
00687  * b64-encoded text included inside the XML file, use "decode". Alternatively, these
00688  * functions can also be used to "encrypt/decrypt" some critical data contained inside
00689  * the XML (it's not a strong encryption at all, but sometimes it can be useful). */
00690 typedef struct XMLDLLENTRY XMLParserBase64Tool
00691 {
00692 public:
00693     XMLParserBase64Tool(): buf(NULL),buflen(0){}
00694     ~XMLParserBase64Tool();
00695     void freeBuffer();///< Call this function when you have finished using this object to release memory used by the internal buffer.
00696 
00697     /**
00698      * @param formatted If "formatted"=true, some space will be reserved for a carriage-return every 72 chars. */
00699     static int encodeLength(int inBufLen, char formatted=0); ///< return the length of the base64 string that encodes a data buffer of size inBufLen bytes.
00700 
00701     /**
00702      * The "base64Encode" function returns a string containing the base64 encoding of "inByteLen" bytes
00703      * from "inByteBuf". If "formatted" parameter is true, then there will be a carriage-return every 72 chars.
00704      * The string will be free'd when the XMLParserBase64Tool object is deleted.
00705      * All returned strings are sharing the same memory space. */
00706     XMLSTR encode(unsigned char *inByteBuf, unsigned int inByteLen, char formatted=0); ///< returns a pointer to an internal buffer containing the base64 string containing the binary data encoded from "inByteBuf"
00707 
00708     /// returns the number of bytes which will be decoded from "inString".
00709     static unsigned int decodeSize(XMLCSTR inString, XMLError *xe=NULL);
00710 
00711     /**
00712      * The "decode" function returns a pointer to a buffer containing the binary data decoded from "inString"
00713      * The output buffer will be free'd when the XMLParserBase64Tool object is deleted.
00714      * All output buffer are sharing the same memory space.
00715      * @param inString If "instring" is malformed, NULL will be returned */
00716     unsigned char* decode(XMLCSTR inString, int *outByteLen=NULL, XMLError *xe=NULL); ///< returns a pointer to an internal buffer containing the binary data decoded from "inString"
00717 
00718     /**
00719      * decodes data from "inString" to "outByteBuf". You need to provide the size (in byte) of "outByteBuf"
00720      * in "inMaxByteOutBuflen". If "outByteBuf" is not large enough or if data is malformed, then "FALSE"
00721      * will be returned; otherwise "TRUE". */
00722     static unsigned char decode(XMLCSTR inString, unsigned char *outByteBuf, int inMaxByteOutBuflen, XMLError *xe=NULL); ///< deprecated.
00723 
00724 private:
00725     void *buf;
00726     int buflen;
00727     void alloc(int newsize);
00728 }XMLParserBase64Tool;
00729 /** @} */
00730 
00731 #undef XMLDLLENTRY
00732 
00733 #endif