You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

726 lines
42 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /****************************************************************************/
  2. /*! \mainpage XMLParser library
  3. * \section intro_sec Introduction
  4. *
  5. * This is a basic XML parser written in ANSI C++ for portability.
  6. * It works by using recursion and a node tree for breaking
  7. * down the elements of an XML document.
  8. *
  9. * @version V2.44
  10. * @author Frank Vanden Berghen
  11. *
  12. * Copyright (c) 2002, Frank Vanden Berghen - All rights reserved.<br/>
  13. * Commercialized by <a href="http://www.Business-Insight.com">Business-Insight</a><br/>
  14. * See the file <a href="../../AFPL-license.txt">AFPL-license.txt</a> about the licensing terms
  15. *
  16. * \section tutorial First Tutorial
  17. * You can follow a simple <a href="../../xmlParser.html">Tutorial</a> to know the basics...
  18. *
  19. * \section usage General usage: How to include the XMLParser library inside your project.
  20. *
  21. * The library is composed of two files: <a href="../../xmlParser.cpp">xmlParser.cpp</a> and
  22. * <a href="../../xmlParser.h">xmlParser.h</a>. These are the ONLY 2 files that you need when
  23. * using the library inside your own projects.
  24. *
  25. * All the functions of the library are documented inside the comments of the file
  26. * <a href="../../xmlParser.h">xmlParser.h</a>. These comments can be transformed in
  27. * full-fledged HTML documentation using the DOXYGEN software: simply type: "doxygen doxy.cfg"
  28. *
  29. * By default, the XMLParser library uses (char*) for string representation.To use the (wchar_t*)
  30. * version of the library, you need to define the "_UNICODE" preprocessor definition variable
  31. * (this is usually done inside your project definition file) (This is done automatically for you
  32. * when using Visual Studio).
  33. *
  34. * \section example Advanced Tutorial and Many Examples of usage.
  35. *
  36. * Some very small introductory examples are described inside the Tutorial file
  37. * <a href="../../xmlParser.html">xmlParser.html</a>
  38. *
  39. * Some additional small examples are also inside the file <a href="../../xmlTest.cpp">xmlTest.cpp</a>
  40. * (for the "char*" version of the library) and inside the file
  41. * <a href="../../xmlTestUnicode.cpp">xmlTestUnicode.cpp</a> (for the "wchar_t*"
  42. * version of the library). If you have a question, please review these additionnal examples
  43. * before sending an e-mail to the author.
  44. *
  45. * To build the examples:
  46. * - linux/unix: type "make"
  47. * - solaris: type "make -f makefile.solaris"
  48. * - windows: Visual Studio: double-click on xmlParser.dsw
  49. * (under Visual Studio .NET, the .dsp and .dsw files will be automatically converted to .vcproj and .sln files)
  50. *
  51. * In order to build the examples you need some additional files:
  52. * - linux/unix: makefile
  53. * - solaris: makefile.solaris
  54. * - windows: Visual Studio: *.dsp, xmlParser.dsw and also xmlParser.lib and xmlParser.dll
  55. *
  56. * \section debugging Debugging with the XMLParser library
  57. *
  58. * \subsection debugwin Debugging under WINDOWS
  59. *
  60. * Inside Visual C++, the "debug versions" of the memory allocation functions are
  61. * very slow: Do not forget to compile in "release mode" to get maximum speed.
  62. * When I had to debug a software that was using the XMLParser Library, it was usually
  63. * a nightmare because the library was sooOOOoooo slow in debug mode (because of the
  64. * slow memory allocations in Debug mode). To solve this
  65. * problem, during all the debugging session, I am now using a very fast DLL version of the
  66. * XMLParser Library (the DLL is compiled in release mode). Using the DLL version of
  67. * the XMLParser Library allows me to have lightening XML parsing speed even in debug!
  68. * Other than that, the DLL version is useless: In the release version of my tool,
  69. * I always use the normal, ".cpp"-based, XMLParser Library (I simply include the
  70. * <a href="../../xmlParser.cpp">xmlParser.cpp</a> and
  71. * <a href="../../xmlParser.h">xmlParser.h</a> files into the project).
  72. *
  73. * The file <a href="../../XMLNodeAutoexp.txt">XMLNodeAutoexp.txt</a> contains some
  74. * "tweaks" that improve substancially the display of the content of the XMLNode objects
  75. * inside the Visual Studio Debugger. Believe me, once you have seen inside the debugger
  76. * the "smooth" display of the XMLNode objects, you cannot live without it anymore!
  77. *
  78. * \subsection debuglinux Debugging under LINUX/UNIX
  79. *
  80. * The speed of the debug version of the XMLParser library is tolerable so no extra
  81. * work.has been done.
  82. *
  83. ****************************************************************************/
  84. #ifndef __INCLUDE_XML_NODE__
  85. #define __INCLUDE_XML_NODE__
  86. #include <stdlib.h>
  87. #if defined(UNICODE) || defined(_UNICODE)
  88. // If you comment the next "define" line then the library will never "switch to" _UNICODE (wchar_t*) mode (16/32 bits per characters).
  89. // This is useful when you get error messages like:
  90. // 'XMLNode::openFileHelper' : cannot convert parameter 2 from 'const char [5]' to 'const wchar_t *'
  91. // The _XMLWIDECHAR preprocessor variable force the XMLParser library into either utf16/32-mode (the proprocessor variable
  92. // must be defined) or utf8-mode(the pre-processor variable must be undefined).
  93. #define _XMLWIDECHAR
  94. #endif
  95. #if defined(WIN32) || defined(UNDER_CE) || defined(_WIN32) || defined(WIN64) || defined(__BORLANDC__)
  96. // comment the next line if you are under windows and the compiler is not Microsoft Visual Studio (6.0 or .NET) or Borland
  97. #define _XMLWINDOWS
  98. #endif
  99. #ifdef XMLDLLENTRY
  100. #undef XMLDLLENTRY
  101. #endif
  102. #ifdef _USE_XMLPARSER_DLL
  103. #ifdef _DLL_EXPORTS_
  104. #define XMLDLLENTRY __declspec(dllexport)
  105. #else
  106. #define XMLDLLENTRY __declspec(dllimport)
  107. #endif
  108. #else
  109. #define XMLDLLENTRY
  110. #endif
  111. // 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)
  112. //#define XML_NO_WIDE_CHAR
  113. #ifdef XML_NO_WIDE_CHAR
  114. #undef _XMLWINDOWS
  115. #undef _XMLWIDECHAR
  116. #endif
  117. #ifdef _XMLWINDOWS
  118. #include <tchar.h>
  119. #else
  120. #define XMLDLLENTRY
  121. #ifndef XML_NO_WIDE_CHAR
  122. #include <wchar.h> // to have 'wcsrtombs' for ANSI version
  123. // to have 'mbsrtowcs' for WIDECHAR version
  124. #endif
  125. #endif
  126. // Some common types for char set portable code
  127. #ifdef _XMLWIDECHAR
  128. #define _CXML(c) L ## c
  129. #define XMLCSTR const wchar_t *
  130. #define XMLSTR wchar_t *
  131. #define XMLCHAR wchar_t
  132. #else
  133. #define _CXML(c) c
  134. #define XMLCSTR const char *
  135. #define XMLSTR char *
  136. #define XMLCHAR char
  137. #endif
  138. #ifndef FALSE
  139. #define FALSE 0
  140. #endif /* FALSE */
  141. #ifndef TRUE
  142. #define TRUE 1
  143. #endif /* TRUE */
  144. /// Enumeration for XML parse errors.
  145. typedef enum E_XMLError{
  146. eXMLErrorNone = 0,
  147. eXMLErrorMissingEndTag = 1,
  148. eXMLErrorNoXMLTagFound,
  149. eXMLErrorEmpty,
  150. eXMLErrorMissingTagName,
  151. eXMLErrorMissingEndTagName,
  152. eXMLErrorUnmatchedEndTag,
  153. eXMLErrorUnmatchedEndClearTag,
  154. eXMLErrorUnexpectedToken,
  155. eXMLErrorNoElements,
  156. eXMLErrorFileNotFound,
  157. eXMLErrorFirstTagNotFound,
  158. eXMLErrorUnknownCharacterEntity,
  159. eXMLErrorCharacterCodeAbove255,
  160. eXMLErrorCharConversionError,
  161. eXMLErrorCannotOpenWriteFile,
  162. eXMLErrorCannotWriteFile,
  163. eXMLErrorBase64DataSizeIsNotMultipleOf4,
  164. eXMLErrorBase64DecodeIllegalCharacter,
  165. eXMLErrorBase64DecodeTruncatedData,
  166. eXMLErrorBase64DecodeBufferTooSmall
  167. } XMLError;
  168. /// Enumeration used to manage type of data. Use in conjunction with structure XMLNodeContents
  169. typedef enum E_XMLElementType{
  170. eNodeChild =0,
  171. eNodeAttribute =1,
  172. eNodeText =2,
  173. eNodeClear =3,
  174. eNodeNULL =4
  175. } XMLElementType;
  176. /// Structure used to obtain error details if the parse fails.
  177. typedef struct S_XMLResults{
  178. XMLError error;
  179. int nLine,nColumn;
  180. } XMLResults;
  181. /// Structure for XML clear (unformatted) node (usually comments)
  182. typedef struct S_XMLClear {
  183. XMLCSTR lpszValue; XMLCSTR lpszOpenTag; XMLCSTR lpszCloseTag;
  184. } XMLClear;
  185. /// Structure for XML attribute.
  186. typedef struct S_XMLAttribute {
  187. XMLCSTR lpszName; XMLCSTR lpszValue;
  188. } XMLAttribute;
  189. /// XMLElementPosition are not interchangeable with simple indexes
  190. typedef int XMLElementPosition;
  191. //struct XMLNodeContents;
  192. struct XMLNode;
  193. /// This structure is given by the function XMLNode::enumContents.
  194. typedef struct S_XMLNodeContents{
  195. /// This dictates what's the content of the XMLNodeContent
  196. XMLElementType etype;
  197. /**< should be an union to access the appropriate data. Compiler does not allow union of object with constructor... too bad. */
  198. XMLNode child;
  199. XMLAttribute attrib;
  200. XMLCSTR text;
  201. XMLClear clear;
  202. } XMLNodeContents;
  203. /** @defgroup XMLParserGeneral The XML parser */
  204. /// Main Class representing a XML node
  205. /**
  206. * All operations are performed using this class.
  207. * \note The constructors of the XMLNode class are protected, so use instead one of these four methods to get your first instance of XMLNode:
  208. * <ul>
  209. * <li> XMLNode::parseString </li>
  210. * <li> XMLNode::parseFile </li>
  211. * <li> XMLNode::openFileHelper </li>
  212. * <li> XMLNode::createXMLTopNode (or XMLNode::createXMLTopNode_WOSD)</li>
  213. * </ul> */
  214. typedef struct XMLDLLENTRY XMLNode{
  215. private:
  216. struct XMLNodeDataTag;
  217. /// Constructors are protected, so use instead one of: XMLNode::parseString, XMLNode::parseFile, XMLNode::openFileHelper, XMLNode::createXMLTopNode
  218. XMLNode(struct XMLNodeDataTag *pParent, XMLSTR lpszName, char isDeclaration);
  219. /// Constructors are protected, so use instead one of: XMLNode::parseString, XMLNode::parseFile, XMLNode::openFileHelper, XMLNode::createXMLTopNode
  220. XMLNode(struct XMLNodeDataTag *p);
  221. public:
  222. static XMLCSTR getVersion();///< Return the XMLParser library version number
  223. /** @defgroup conversions Parsing XML files/strings to an XMLNode structure and Rendering XMLNode's to files/string.
  224. * @ingroup XMLParserGeneral
  225. * @{ */
  226. /// Parse an XML string and return the root of a XMLNode tree representing the string.
  227. static XMLNode parseString (XMLCSTR lpXMLString, XMLCSTR tag=NULL, XMLResults *pResults=NULL);
  228. /**< The "parseString" function parse an XML string and return the root of a XMLNode tree. The "opposite" of this function is
  229. * the function "createXMLString" that re-creates an XML string from an XMLNode tree. If the XML document is corrupted, the
  230. * "parseString" method will initialize the "pResults" variable with some information that can be used to trace the error.
  231. * If you still want to parse the file, you can use the APPROXIMATE_PARSING option as explained inside the note at the
  232. * beginning of the "xmlParser.cpp" file.
  233. *
  234. * @param lpXMLString the XML string to parse
  235. * @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 (<? ... ?>).
  236. * @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.
  237. */
  238. /// Parse an XML file and return the root of a XMLNode tree representing the file.
  239. static XMLNode parseFile (XMLCSTR filename, XMLCSTR tag=NULL, XMLResults *pResults=NULL);
  240. /**< The "parseFile" function parse an XML file and return the root of a XMLNode tree. The "opposite" of this function is
  241. * the function "writeToFile" that re-creates an XML file from an XMLNode tree. If the XML document is corrupted, the
  242. * "parseFile" method will initialize the "pResults" variable with some information that can be used to trace the error.
  243. * If you still want to parse the file, you can use the APPROXIMATE_PARSING option as explained inside the note at the
  244. * beginning of the "xmlParser.cpp" file.
  245. *
  246. * @param filename the path to the XML file to parse
  247. * @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 (<? ... ?>).
  248. * @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.
  249. */
  250. /// 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.
  251. static XMLNode openFileHelper(XMLCSTR filename, XMLCSTR tag=NULL);
  252. /**< The "openFileHelper" function reports to the screen all the warnings and errors that occurred during parsing of the XML file.
  253. * 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
  254. * application has its own way to report and deal with errors, you should rather use the "parseFile" function to parse XML files
  255. * and program yourself thereafter an "error reporting" tailored for your needs (instead of using the very crude "error reporting"
  256. * mechanism included inside the "openFileHelper" function).
  257. *
  258. * If the XML document is corrupted, the "openFileHelper" method will:
  259. * - display an error message on the console (or inside a messageBox for windows).
  260. * - stop execution (exit).
  261. *
  262. * I strongly suggest that you write your own "openFileHelper" method tailored to your needs. If you still want to parse
  263. * the file, you can use the APPROXIMATE_PARSING option as explained inside the note at the beginning of the "xmlParser.cpp" file.
  264. *
  265. * @param filename the path of the XML file to parse.
  266. * @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 (<? ... ?>).
  267. */
  268. static XMLCSTR getError(XMLError error); ///< this gives you a user-friendly explanation of the parsing error
  269. /// Create an XML string starting from the current XMLNode.
  270. XMLSTR createXMLString(int nFormat=1, int *pnSize=NULL) const;
  271. /**< The returned string should be free'd using the "freeXMLString" function.
  272. *
  273. * If nFormat==0, no formatting is required otherwise this returns an user friendly XML string from a given element
  274. * with appropriate white spaces and carriage returns. if pnSize is given it returns the size in character of the string. */
  275. /// Save the content of an xmlNode inside a file
  276. XMLError writeToFile(XMLCSTR filename,
  277. const char *encoding=NULL,
  278. char nFormat=1) const;
  279. /**< 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.
  280. * If the global parameter "characterEncoding==encoding_UTF8", then the "encoding" parameter is ignored and always set to "utf-8".
  281. * If the global parameter "characterEncoding==encoding_ShiftJIS", then the "encoding" parameter is ignored and always set to "SHIFT-JIS".
  282. * If "_XMLWIDECHAR=1", then the "encoding" parameter is ignored and always set to "utf-16".
  283. * If no "encoding" parameter is given the "ISO-8859-1" encoding is used. */
  284. /** @} */
  285. /** @defgroup navigate Navigate the XMLNode structure
  286. * @ingroup XMLParserGeneral
  287. * @{ */
  288. XMLCSTR getName() const; ///< name of the node
  289. XMLCSTR getText(int i=0) const; ///< return ith text field
  290. int nText() const; ///< nbr of text field
  291. XMLNode getParentNode() const; ///< return the parent node
  292. XMLNode getChildNode(int i=0) const; ///< return ith child node
  293. 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.
  294. XMLNode getChildNode(XMLCSTR name, int *i=NULL) const; ///< return next child node with specific name (return an empty node if failing)
  295. XMLNode getChildNodeWithAttribute(XMLCSTR tagName,
  296. XMLCSTR attributeName,
  297. XMLCSTR attributeValue=NULL,
  298. int *i=NULL) const; ///< return child node with specific name/attribute (return an empty node if failing)
  299. XMLNode getChildNodeByPath(XMLCSTR path, char createNodeIfMissing=0, XMLCHAR sep='/');
  300. ///< return the first child node with specific path
  301. XMLNode getChildNodeByPathNonConst(XMLSTR path, char createNodeIfMissing=0, XMLCHAR sep='/');
  302. ///< return the first child node with specific path.
  303. int nChildNode(XMLCSTR name) const; ///< return the number of child node with specific name
  304. int nChildNode() const; ///< nbr of child node
  305. XMLAttribute getAttribute(int i=0) const; ///< return ith attribute
  306. XMLCSTR getAttributeName(int i=0) const; ///< return ith attribute name
  307. XMLCSTR getAttributeValue(int i=0) const; ///< return ith attribute value
  308. char isAttributeSet(XMLCSTR name) const; ///< test if an attribute with a specific name is given
  309. XMLCSTR getAttribute(XMLCSTR name, int i) const; ///< return ith attribute content with specific name (return a NULL if failing)
  310. XMLCSTR getAttribute(XMLCSTR name, int *i=NULL) const; ///< return next attribute content with specific name (return a NULL if failing)
  311. int nAttribute() const; ///< nbr of attribute
  312. XMLClear getClear(int i=0) const; ///< return ith clear field (comments)
  313. int nClear() const; ///< nbr of clear field
  314. 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();
  315. int nElement() const; ///< nbr of different contents for current node
  316. char isEmpty() const; ///< is this node Empty?
  317. char isDeclaration() const; ///< is this node a declaration <? .... ?>
  318. XMLNode deepCopy() const; ///< deep copy (duplicate/clone) a XMLNode
  319. static XMLNode emptyNode(); ///< return XMLNode::emptyXMLNode;
  320. /** @} */
  321. ~XMLNode();
  322. XMLNode(const XMLNode &A); ///< to allow shallow/fast copy:
  323. XMLNode& operator=( const XMLNode& A ); ///< to allow shallow/fast copy:
  324. XMLNode(): d(NULL){};
  325. static XMLNode emptyXMLNode;
  326. static XMLClear emptyXMLClear;
  327. static XMLAttribute emptyXMLAttribute;
  328. /** @defgroup xmlModify Create or Update the XMLNode structure
  329. * @ingroup XMLParserGeneral
  330. * The functions in this group allows you to create from scratch (or update) a XMLNode structure. Start by creating your top
  331. * node with the "createXMLTopNode" function and then add new nodes with the "addChild" function. The parameter 'pos' gives
  332. * the position where the childNode, the text or the XMLClearTag will be inserted. The default value (pos=-1) inserts at the
  333. * end. The value (pos=0) insert at the beginning (Insertion at the beginning is slower than at the end). <br>
  334. *
  335. * REMARK: 0 <= pos < nChild()+nText()+nClear() <br>
  336. */
  337. /** @defgroup creation Creating from scratch a XMLNode structure
  338. * @ingroup xmlModify
  339. * @{ */
  340. static XMLNode createXMLTopNode(XMLCSTR lpszName, char isDeclaration=FALSE); ///< Create the top node of an XMLNode structure
  341. XMLNode addChild(XMLCSTR lpszName, char isDeclaration=FALSE, XMLElementPosition pos=-1); ///< Add a new child node
  342. 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
  343. XMLAttribute *addAttribute(XMLCSTR lpszName, XMLCSTR lpszValuev); ///< Add a new attribute
  344. XMLCSTR addText(XMLCSTR lpszValue, XMLElementPosition pos=-1); ///< Add a new text content
  345. XMLClear *addClear(XMLCSTR lpszValue, XMLCSTR lpszOpen=NULL, XMLCSTR lpszClose=NULL, XMLElementPosition pos=-1);
  346. /**< Add a new clear tag
  347. * @param lpszOpen default value "<![CDATA["
  348. * @param lpszClose default value "]]>"
  349. */
  350. /** @} */
  351. /** @defgroup xmlUpdate Updating Nodes
  352. * @ingroup xmlModify
  353. * Some update functions:
  354. * @{
  355. */
  356. XMLCSTR updateName(XMLCSTR lpszName); ///< change node's name
  357. XMLAttribute *updateAttribute(XMLAttribute *newAttribute, XMLAttribute *oldAttribute); ///< if the attribute to update is missing, a new one will be added
  358. XMLAttribute *updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName=NULL,int i=0); ///< if the attribute to update is missing, a new one will be added
  359. 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
  360. XMLCSTR updateText(XMLCSTR lpszNewValue, int i=0); ///< if the text to update is missing, a new one will be added
  361. XMLCSTR updateText(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue); ///< if the text to update is missing, a new one will be added
  362. XMLClear *updateClear(XMLCSTR lpszNewContent, int i=0); ///< if the clearTag to update is missing, a new one will be added
  363. XMLClear *updateClear(XMLClear *newP,XMLClear *oldP); ///< if the clearTag to update is missing, a new one will be added
  364. XMLClear *updateClear(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue); ///< if the clearTag to update is missing, a new one will be added
  365. /** @} */
  366. /** @defgroup xmlDelete Deleting Nodes or Attributes
  367. * @ingroup xmlModify
  368. * Some deletion functions:
  369. * @{
  370. */
  371. /// The "deleteNodeContent" function forces the deletion of the content of this XMLNode and the subtree.
  372. void deleteNodeContent();
  373. /**< \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. */
  374. void deleteAttribute(int i=0); ///< Delete the ith attribute of the current XMLNode
  375. void deleteAttribute(XMLCSTR lpszName); ///< Delete the attribute with the given name (the "strcmp" function is used to find the right attribute)
  376. void deleteAttribute(XMLAttribute *anAttribute); ///< Delete the attribute with the name "anAttribute->lpszName" (the "strcmp" function is used to find the right attribute)
  377. void deleteText(int i=0); ///< Delete the Ith text content of the current XMLNode
  378. 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)
  379. void deleteClear(int i=0); ///< Delete the Ith clear tag inside the current XMLNode
  380. 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)
  381. 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)
  382. /** @} */
  383. /** @defgroup xmlWOSD ???_WOSD functions.
  384. * @ingroup xmlModify
  385. * The strings given as parameters for the "add" and "update" methods that have a name with
  386. * the postfix "_WOSD" (that means "WithOut String Duplication")(for example "addText_WOSD")
  387. * will be free'd by the XMLNode class. For example, it means that this is incorrect:
  388. * \code
  389. * xNode.addText_WOSD("foo");
  390. * xNode.updateAttribute_WOSD("#newcolor" ,NULL,"color");
  391. * \endcode
  392. * In opposition, this is correct:
  393. * \code
  394. * xNode.addText("foo");
  395. * xNode.addText_WOSD(stringDup("foo"));
  396. * xNode.updateAttribute("#newcolor" ,NULL,"color");
  397. * xNode.updateAttribute_WOSD(stringDup("#newcolor"),NULL,"color");
  398. * \endcode
  399. * Typically, you will never do:
  400. * \code
  401. * char *b=(char*)malloc(...);
  402. * xNode.addText(b);
  403. * free(b);
  404. * \endcode
  405. * ... but rather:
  406. * \code
  407. * char *b=(char*)malloc(...);
  408. * xNode.addText_WOSD(b);
  409. * \endcode
  410. * ('free(b)' is performed by the XMLNode class)
  411. * @{ */
  412. static XMLNode createXMLTopNode_WOSD(XMLSTR lpszName, char isDeclaration=FALSE); ///< Create the top node of an XMLNode structure
  413. XMLNode addChild_WOSD(XMLSTR lpszName, char isDeclaration=FALSE, XMLElementPosition pos=-1); ///< Add a new child node
  414. XMLAttribute *addAttribute_WOSD(XMLSTR lpszName, XMLSTR lpszValue); ///< Add a new attribute
  415. XMLCSTR addText_WOSD(XMLSTR lpszValue, XMLElementPosition pos=-1); ///< Add a new text content
  416. XMLClear *addClear_WOSD(XMLSTR lpszValue, XMLCSTR lpszOpen=NULL, XMLCSTR lpszClose=NULL, XMLElementPosition pos=-1); ///< Add a new clear Tag
  417. XMLCSTR updateName_WOSD(XMLSTR lpszName); ///< change node's name
  418. XMLAttribute *updateAttribute_WOSD(XMLAttribute *newAttribute, XMLAttribute *oldAttribute); ///< if the attribute to update is missing, a new one will be added
  419. XMLAttribute *updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName=NULL,int i=0); ///< if the attribute to update is missing, a new one will be added
  420. 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
  421. XMLCSTR updateText_WOSD(XMLSTR lpszNewValue, int i=0); ///< if the text to update is missing, a new one will be added
  422. XMLCSTR updateText_WOSD(XMLSTR lpszNewValue, XMLCSTR lpszOldValue); ///< if the text to update is missing, a new one will be added
  423. XMLClear *updateClear_WOSD(XMLSTR lpszNewContent, int i=0); ///< if the clearTag to update is missing, a new one will be added
  424. XMLClear *updateClear_WOSD(XMLClear *newP,XMLClear *oldP); ///< if the clearTag to update is missing, a new one will be added
  425. XMLClear *updateClear_WOSD(XMLSTR lpszNewValue, XMLCSTR lpszOldValue); ///< if the clearTag to update is missing, a new one will be added
  426. /** @} */
  427. /** @defgroup xmlPosition Position helper functions (use in conjunction with the update&add functions
  428. * @ingroup xmlModify
  429. * These are some useful functions when you want to insert a childNode, a text or a XMLClearTag in the
  430. * middle (at a specified position) of a XMLNode tree already constructed. The value returned by these
  431. * methods is to be used as last parameter (parameter 'pos') of addChild, addText or addClear.
  432. * @{ */
  433. XMLElementPosition positionOfText(int i=0) const;
  434. XMLElementPosition positionOfText(XMLCSTR lpszValue) const;
  435. XMLElementPosition positionOfClear(int i=0) const;
  436. XMLElementPosition positionOfClear(XMLCSTR lpszValue) const;
  437. XMLElementPosition positionOfClear(XMLClear *a) const;
  438. XMLElementPosition positionOfChildNode(int i=0) const;
  439. XMLElementPosition positionOfChildNode(XMLNode x) const;
  440. 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
  441. /** @} */
  442. /// Enumeration for XML character encoding.
  443. typedef enum XMLCharEncoding
  444. {
  445. char_encoding_error=0,
  446. char_encoding_UTF8=1,
  447. char_encoding_legacy=2,
  448. char_encoding_ShiftJIS=3,
  449. char_encoding_GB2312=4,
  450. char_encoding_Big5=5,
  451. char_encoding_GBK=6 // this is actually the same as Big5
  452. } XMLCharEncoding;
  453. /** \addtogroup conversions
  454. * @{ */
  455. /// Sets the global options for the conversions
  456. static char setGlobalOptions(XMLCharEncoding characterEncoding=XMLNode::char_encoding_UTF8, char guessWideCharChars=1,
  457. char dropWhiteSpace=1, char removeCommentsInMiddleOfText=1);
  458. /**< The "setGlobalOptions" function allows you to change four global parameters that affect string & file
  459. * parsing. First of all, you most-probably will never have to change these 3 global parameters.
  460. *
  461. * @param guessWideCharChars If "guessWideCharChars"=1 and if this library is compiled in WideChar mode, then the
  462. * XMLNode::parseFile and XMLNode::openFileHelper functions will test if the file contains ASCII
  463. * characters. If this is the case, then the file will be loaded and converted in memory to
  464. * WideChar before being parsed. If 0, no conversion will be performed.
  465. *
  466. * @param guessWideCharChars If "guessWideCharChars"=1 and if this library is compiled in ASCII/UTF8/char* mode, then the
  467. * XMLNode::parseFile and XMLNode::openFileHelper functions will test if the file contains WideChar
  468. * characters. If this is the case, then the file will be loaded and converted in memory to
  469. * ASCII/UTF8/char* before being parsed. If 0, no conversion will be performed.
  470. *
  471. * @param characterEncoding This parameter is only meaningful when compiling in char* mode (multibyte character mode).
  472. * In wchar_t* (wide char mode), this parameter is ignored. This parameter should be one of the
  473. * three currently recognized encodings: XMLNode::encoding_UTF8, XMLNode::encoding_ascii,
  474. * XMLNode::encoding_ShiftJIS.
  475. *
  476. * @param dropWhiteSpace In most situations, text fields containing only white spaces (and carriage returns)
  477. * are useless. Even more, these "empty" text fields are annoying because they increase the
  478. * complexity of the user's code for parsing. So, 99% of the time, it's better to drop
  479. * the "empty" text fields. However The XML specification indicates that no white spaces
  480. * should be lost when parsing the file. So to be perfectly XML-compliant, you should set
  481. * dropWhiteSpace=0. A note of caution: if you set "dropWhiteSpace=0", the parser will be
  482. * slower and your code will be more complex.
  483. *
  484. * @param removeCommentsInMiddleOfText To explain this parameter, let's consider this code:
  485. * \code
  486. * XMLNode x=XMLNode::parseString("<a>foo<!-- hello -->bar<!DOCTYPE world >chu</a>","a");
  487. * \endcode
  488. * If removeCommentsInMiddleOfText=0, then we will have:
  489. * \code
  490. * x.getText(0) -> "foo"
  491. * x.getText(1) -> "bar"
  492. * x.getText(2) -> "chu"
  493. * x.getClear(0) --> "<!-- hello -->"
  494. * x.getClear(1) --> "<!DOCTYPE world >"
  495. * \endcode
  496. * If removeCommentsInMiddleOfText=1, then we will have:
  497. * \code
  498. * x.getText(0) -> "foobar"
  499. * x.getText(1) -> "chu"
  500. * x.getClear(0) --> "<!DOCTYPE world >"
  501. * \endcode
  502. *
  503. * \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.
  504. *
  505. * \note Sometime, it's useful to set "guessWideCharChars=0" to disable any conversion
  506. * because the test to detect the file-type (ASCII/UTF8/char* or WideChar) may fail (rarely). */
  507. /// Guess the character encoding of the string (ascii, utf8 or shift-JIS)
  508. static XMLCharEncoding guessCharEncoding(void *buffer, int bufLen, char useXMLEncodingAttribute=1);
  509. /**< The "guessCharEncoding" function try to guess the character encoding. You most-probably will never
  510. * have to use this function. It then returns the appropriate value of the global parameter
  511. * "characterEncoding" described in the XMLNode::setGlobalOptions. The guess is based on the content of a buffer of length
  512. * "bufLen" bytes that contains the first bytes (minimum 25 bytes; 200 bytes is a good value) of the
  513. * file to be parsed. The XMLNode::openFileHelper function is using this function to automatically compute
  514. * the value of the "characterEncoding" global parameter. There are several heuristics used to do the
  515. * guess. One of the heuristic is based on the "encoding" attribute. The original XML specifications
  516. * forbids to use this attribute to do the guess but you can still use it if you set
  517. * "useXMLEncodingAttribute" to 1 (this is the default behavior and the behavior of most parsers).
  518. * If an inconsistency in the encoding is detected, then the return value is "0". */
  519. /** @} */
  520. private:
  521. // these are functions and structures used internally by the XMLNode class (don't bother about them):
  522. typedef struct XMLNodeDataTag // to allow shallow copy and "intelligent/smart" pointers (automatic delete):
  523. {
  524. XMLCSTR lpszName; // Element name (=NULL if root)
  525. int nChild, // Number of child nodes
  526. nText, // Number of text fields
  527. nClear, // Number of Clear fields (comments)
  528. nAttribute; // Number of attributes
  529. char isDeclaration; // Whether node is an XML declaration - '<?xml ?>'
  530. struct XMLNodeDataTag *pParent; // Pointer to parent element (=NULL if root)
  531. XMLNode *pChild; // Array of child nodes
  532. XMLCSTR *pText; // Array of text fields
  533. XMLClear *pClear; // Array of clear fields
  534. XMLAttribute *pAttribute; // Array of attributes
  535. int *pOrder; // order of the child_nodes,text_fields,clear_fields
  536. int ref_count; // for garbage collection (smart pointers)
  537. } XMLNodeData;
  538. XMLNodeData *d;
  539. char parseClearTag(void *px, void *pa);
  540. char maybeAddTxT(void *pa, XMLCSTR tokenPStr);
  541. int ParseXMLElement(void *pXML);
  542. void *addToOrder(int memInc, int *_pos, int nc, void *p, int size, XMLElementType xtype);
  543. int indexText(XMLCSTR lpszValue) const;
  544. int indexClear(XMLCSTR lpszValue) const;
  545. XMLNode addChild_priv(int,XMLSTR,char,int);
  546. XMLAttribute *addAttribute_priv(int,XMLSTR,XMLSTR);
  547. XMLCSTR addText_priv(int,XMLSTR,int);
  548. XMLClear *addClear_priv(int,XMLSTR,XMLCSTR,XMLCSTR,int);
  549. void emptyTheNode(char force);
  550. static inline XMLElementPosition findPosition(XMLNodeData *d, int index, XMLElementType xtype);
  551. static int CreateXMLStringR(XMLNodeData *pEntry, XMLSTR lpszMarker, int nFormat);
  552. static int removeOrderElement(XMLNodeData *d, XMLElementType t, int index);
  553. static void exactMemory(XMLNodeData *d);
  554. static int detachFromParent(XMLNodeData *d);
  555. } XMLNode;
  556. /** @defgroup StringAlloc String Allocation/Free functions
  557. * @ingroup xmlModify
  558. * @{ */
  559. /// Duplicate (copy in a new allocated buffer) the source string.
  560. XMLDLLENTRY XMLSTR stringDup(XMLCSTR source, int cbData=-1);
  561. /**< This is
  562. * a very handy function when used with all the "XMLNode::*_WOSD" functions (\link xmlWOSD \endlink).
  563. * @param cbData If !=0 then cbData is the number of chars to duplicate. New strings allocated with
  564. * this function should be free'd using the "freeXMLString" function. */
  565. /// to free the string allocated inside the "stringDup" function or the "createXMLString" function.
  566. XMLDLLENTRY void freeXMLString(XMLSTR t); // {free(t);}
  567. /** @} */
  568. /** @defgroup atoX ato? like functions
  569. * @ingroup XMLParserGeneral
  570. * The "xmlto?" functions are equivalents to the atoi, atol, atof functions.
  571. * The only difference is: If the variable "xmlString" is NULL, than the return value
  572. * is "defautValue". These 6 functions are only here as "convenience" functions for the
  573. * user (they are not used inside the XMLparser). If you don't need them, you can
  574. * delete them without any trouble.
  575. *
  576. * @{ */
  577. XMLDLLENTRY char xmltob(XMLCSTR xmlString,char defautValue=0);
  578. XMLDLLENTRY int xmltoi(XMLCSTR xmlString,int defautValue=0);
  579. XMLDLLENTRY long long xmltol(XMLCSTR xmlString,long long defautValue=0);
  580. XMLDLLENTRY double xmltof(XMLCSTR xmlString,double defautValue=.0);
  581. XMLDLLENTRY XMLCSTR xmltoa(XMLCSTR xmlString,XMLCSTR defautValue=_CXML(""));
  582. XMLDLLENTRY XMLCHAR xmltoc(XMLCSTR xmlString,const XMLCHAR defautValue=_CXML('\0'));
  583. /** @} */
  584. /** @defgroup ToXMLStringTool Helper class to create XML files using "printf", "fprintf", "cout",... functions.
  585. * @ingroup XMLParserGeneral
  586. * @{ */
  587. /// Helper class to create XML files using "printf", "fprintf", "cout",... functions.
  588. /** The ToXMLStringTool class helps you creating XML files using "printf", "fprintf", "cout",... functions.
  589. * The "ToXMLStringTool" class is processing strings so that all the characters
  590. * &,",',<,> are replaced by their XML equivalent:
  591. * \verbatim &amp;, &quot;, &apos;, &lt;, &gt; \endverbatim
  592. * Using the "ToXMLStringTool class" and the "fprintf function" is THE most efficient
  593. * way to produce VERY large XML documents VERY fast.
  594. * \note If you are creating from scratch an XML file using the provided XMLNode class
  595. * you must not use the "ToXMLStringTool" class (because the "XMLNode" class does the
  596. * processing job for you during rendering).*/
  597. typedef struct XMLDLLENTRY ToXMLStringTool
  598. {
  599. public:
  600. ToXMLStringTool(): buf(NULL),buflen(0){}
  601. ~ToXMLStringTool();
  602. void freeBuffer();///<call this function when you have finished using this object to release memory used by the internal buffer.
  603. XMLSTR toXML(XMLCSTR source);///< returns a pointer to an internal buffer that contains a XML-encoded string based on the "source" parameter.
  604. /** The "toXMLUnSafe" function is deprecated because there is a possibility of
  605. * "destination-buffer-overflow". It converts the string
  606. * "source" to the string "dest". */
  607. static XMLSTR toXMLUnSafe(XMLSTR dest,XMLCSTR source); ///< deprecated: use "toXML" instead
  608. static int lengthXMLString(XMLCSTR source); ///< deprecated: use "toXML" instead
  609. private:
  610. XMLSTR buf;
  611. int buflen;
  612. } ToXMLStringTool;
  613. /** @} */
  614. /** @defgroup XMLParserBase64Tool Helper class to include binary data inside XML strings using "Base64 encoding".
  615. * @ingroup XMLParserGeneral
  616. * @{ */
  617. /// Helper class to include binary data inside XML strings using "Base64 encoding".
  618. /** The "XMLParserBase64Tool" class allows you to include any binary data (images, sounds,...)
  619. * into an XML document using "Base64 encoding". This class is completely
  620. * separated from the rest of the xmlParser library and can be removed without any problem.
  621. * To include some binary data into an XML file, you must convert the binary data into
  622. * standard text (using "encode"). To retrieve the original binary data from the
  623. * b64-encoded text included inside the XML file, use "decode". Alternatively, these
  624. * functions can also be used to "encrypt/decrypt" some critical data contained inside
  625. * the XML (it's not a strong encryption at all, but sometimes it can be useful). */
  626. typedef struct XMLDLLENTRY XMLParserBase64Tool
  627. {
  628. public:
  629. XMLParserBase64Tool(): buf(NULL),buflen(0){}
  630. ~XMLParserBase64Tool();
  631. void freeBuffer();///< Call this function when you have finished using this object to release memory used by the internal buffer.
  632. /**
  633. * @param formatted If "formatted"=true, some space will be reserved for a carriage-return every 72 chars. */
  634. static int encodeLength(int inBufLen, char formatted=0); ///< return the length of the base64 string that encodes a data buffer of size inBufLen bytes.
  635. /**
  636. * The "base64Encode" function returns a string containing the base64 encoding of "inByteLen" bytes
  637. * from "inByteBuf". If "formatted" parameter is true, then there will be a carriage-return every 72 chars.
  638. * The string will be free'd when the XMLParserBase64Tool object is deleted.
  639. * All returned strings are sharing the same memory space. */
  640. 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"
  641. /// returns the number of bytes which will be decoded from "inString".
  642. static unsigned int decodeSize(XMLCSTR inString, XMLError *xe=NULL);
  643. /**
  644. * The "decode" function returns a pointer to a buffer containing the binary data decoded from "inString"
  645. * The output buffer will be free'd when the XMLParserBase64Tool object is deleted.
  646. * All output buffer are sharing the same memory space.
  647. * @param inString If "instring" is malformed, NULL will be returned */
  648. 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"
  649. /**
  650. * decodes data from "inString" to "outByteBuf". You need to provide the size (in byte) of "outByteBuf"
  651. * in "inMaxByteOutBuflen". If "outByteBuf" is not large enough or if data is malformed, then "FALSE"
  652. * will be returned; otherwise "TRUE". */
  653. static unsigned char decode(XMLCSTR inString, unsigned char *outByteBuf, int inMaxByteOutBuflen, XMLError *xe=NULL); ///< deprecated.
  654. private:
  655. void *buf;
  656. int buflen;
  657. void alloc(int newsize);
  658. }XMLParserBase64Tool;
  659. /** @} */
  660. #undef XMLDLLENTRY
  661. #endif