PageRenderTime 76ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 1ms

/xmlParser/xmlParser.cpp

https://bitbucket.org/salehqt/nifty_sim
C++ | 2917 lines | 2289 code | 228 blank | 400 comment | 470 complexity | 540a05219506bd5322450996946e23b2 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. /**
  2. ****************************************************************************
  3. * <P> XML.c - implementation file for basic XML parser written in ANSI C++
  4. * for portability. It works by using recursion and a node tree for breaking
  5. * down the elements of an XML document. </P>
  6. *
  7. * @version V2.41
  8. * @author Frank Vanden Berghen
  9. *
  10. * NOTE:
  11. *
  12. * If you add "#define STRICT_PARSING", on the first line of this file
  13. * the parser will see the following XML-stream:
  14. * <a><b>some text</b><b>other text </a>
  15. * as an error. Otherwise, this tring will be equivalent to:
  16. * <a><b>some text</b><b>other text</b></a>
  17. *
  18. * NOTE:
  19. *
  20. * If you add "#define APPROXIMATE_PARSING" on the first line of this file
  21. * the parser will see the following XML-stream:
  22. * <data name="n1">
  23. * <data name="n2">
  24. * <data name="n3" />
  25. * as equivalent to the following XML-stream:
  26. * <data name="n1" />
  27. * <data name="n2" />
  28. * <data name="n3" />
  29. * This can be useful for badly-formed XML-streams but prevent the use
  30. * of the following XML-stream (problem is: tags at contiguous levels
  31. * have the same names):
  32. * <data name="n1">
  33. * <data name="n2">
  34. * <data name="n3" />
  35. * </data>
  36. * </data>
  37. *
  38. * NOTE:
  39. *
  40. * If you add "#define _XMLPARSER_NO_MESSAGEBOX_" on the first line of this file
  41. * the "openFileHelper" function will always display error messages inside the
  42. * console instead of inside a message-box-window. Message-box-windows are
  43. * available on windows 9x/NT/2000/XP/Vista only.
  44. *
  45. * The following license terms apply to projects that are in some way related to
  46. * the "Nifty Sim project", including applications
  47. * using "Nifty Sim project" and tools developed
  48. * for enhancing "Nifty Sim project". All other projects
  49. * (not related to "Nifty Sim project") have to use this
  50. * code under the Aladdin Free Public License (AFPL)
  51. * See the file "AFPL-license.txt" for more informations about the AFPL license.
  52. * (see http://www.artifex.com/downloads/doc/Public.htm for detailed AFPL terms)
  53. *
  54. * Redistribution and use in source and binary forms, with or without
  55. * modification, are permitted provided that the following conditions are met:
  56. * * Redistributions of source code must retain the above copyright
  57. * notice, this list of conditions and the following disclaimer.
  58. * * Redistributions in binary form must reproduce the above copyright
  59. * notice, this list of conditions and the following disclaimer in the
  60. * documentation and/or other materials provided with the distribution.
  61. * * Neither the name of Frank Vanden Berghen nor the
  62. * names of its contributors may be used to endorse or promote products
  63. * derived from this software without specific prior written permission.
  64. *
  65. * THIS SOFTWARE IS PROVIDED BY Business-Insight ``AS IS'' AND ANY
  66. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  67. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  68. * DISCLAIMED. IN NO EVENT SHALL Business-Insight BE LIABLE FOR ANY
  69. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  70. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  71. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  72. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  73. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  74. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  75. *
  76. * Copyright (c) 2002, Business-Insight
  77. * <a href="http://www.Business-Insight.com">Business-Insight</a>
  78. * All rights reserved.
  79. *
  80. ****************************************************************************
  81. */
  82. #ifndef _CRT_SECURE_NO_DEPRECATE
  83. #define _CRT_SECURE_NO_DEPRECATE
  84. #endif
  85. #include "xmlParser.h"
  86. #ifdef _XMLWINDOWS
  87. //#ifdef _DEBUG
  88. //#define _CRTDBG_MAP_ALLOC
  89. //#include <crtdbg.h>
  90. //#endif
  91. #define WIN32_LEAN_AND_MEAN
  92. #include <Windows.h> // to have IsTextUnicode, MultiByteToWideChar, WideCharToMultiByte to handle unicode files
  93. // to have "MessageBoxA" to display error messages for openFilHelper
  94. #endif
  95. #include <memory.h>
  96. #include <assert.h>
  97. #include <stdio.h>
  98. #include <string.h>
  99. #include <stdlib.h>
  100. XMLCSTR XMLNode::getVersion() { return _CXML("v2.41"); }
  101. void freeXMLString(XMLSTR t){if(t)free(t);}
  102. static XMLNode::XMLCharEncoding characterEncoding=XMLNode::char_encoding_UTF8;
  103. static char guessWideCharChars=1, dropWhiteSpace=1, removeCommentsInMiddleOfText=1;
  104. inline int mmin( const int t1, const int t2 ) { return t1 < t2 ? t1 : t2; }
  105. // You can modify the initialization of the variable "XMLClearTags" below
  106. // to change the clearTags that are currently recognized by the library.
  107. // The number on the second columns is the length of the string inside the
  108. // first column. The "<!DOCTYPE" declaration must be the second in the list.
  109. // The "<!--" declaration must be the third in the list.
  110. typedef struct { XMLCSTR lpszOpen; int openTagLen; XMLCSTR lpszClose;} ALLXMLClearTag;
  111. static ALLXMLClearTag XMLClearTags[] =
  112. {
  113. { _CXML("<![CDATA["),9, _CXML("]]>") },
  114. { _CXML("<!DOCTYPE"),9, _CXML(">") },
  115. { _CXML("<!--") ,4, _CXML("-->") },
  116. { _CXML("<PRE>") ,5, _CXML("</PRE>") },
  117. // { _CXML("<Script>") ,8, _CXML("</Script>")},
  118. { NULL ,0, NULL }
  119. };
  120. // You can modify the initialization of the variable "XMLEntities" below
  121. // to change the character entities that are currently recognized by the library.
  122. // The number on the second columns is the length of the string inside the
  123. // first column. Additionally, the syntaxes "&#xA0;" and "&#160;" are recognized.
  124. typedef struct { XMLCSTR s; int l; XMLCHAR c;} XMLCharacterEntity;
  125. static XMLCharacterEntity XMLEntities[] =
  126. {
  127. { _CXML("&amp;" ), 5, _CXML('&' )},
  128. { _CXML("&lt;" ), 4, _CXML('<' )},
  129. { _CXML("&gt;" ), 4, _CXML('>' )},
  130. { _CXML("&quot;"), 6, _CXML('\"')},
  131. { _CXML("&apos;"), 6, _CXML('\'')},
  132. { NULL , 0, '\0' }
  133. };
  134. // When rendering the XMLNode to a string (using the "createXMLString" function),
  135. // you can ask for a beautiful formatting. This formatting is using the
  136. // following indentation character:
  137. #define INDENTCHAR _CXML('\t')
  138. // The following function parses the XML errors into a user friendly string.
  139. // You can edit this to change the output language of the library to something else.
  140. XMLCSTR XMLNode::getError(XMLError xerror)
  141. {
  142. switch (xerror)
  143. {
  144. case eXMLErrorNone: return _CXML("No error");
  145. case eXMLErrorMissingEndTag: return _CXML("Warning: Unmatched end tag");
  146. case eXMLErrorNoXMLTagFound: return _CXML("Warning: No XML tag found");
  147. case eXMLErrorEmpty: return _CXML("Error: No XML data");
  148. case eXMLErrorMissingTagName: return _CXML("Error: Missing start tag name");
  149. case eXMLErrorMissingEndTagName: return _CXML("Error: Missing end tag name");
  150. case eXMLErrorUnmatchedEndTag: return _CXML("Error: Unmatched end tag");
  151. case eXMLErrorUnmatchedEndClearTag: return _CXML("Error: Unmatched clear tag end");
  152. case eXMLErrorUnexpectedToken: return _CXML("Error: Unexpected token found");
  153. case eXMLErrorNoElements: return _CXML("Error: No elements found");
  154. case eXMLErrorFileNotFound: return _CXML("Error: File not found");
  155. case eXMLErrorFirstTagNotFound: return _CXML("Error: First Tag not found");
  156. case eXMLErrorUnknownCharacterEntity:return _CXML("Error: Unknown character entity");
  157. case eXMLErrorCharacterCodeAbove255: return _CXML("Error: Character code above 255 is forbidden in MultiByte char mode.");
  158. case eXMLErrorCharConversionError: return _CXML("Error: unable to convert between WideChar and MultiByte chars");
  159. case eXMLErrorCannotOpenWriteFile: return _CXML("Error: unable to open file for writing");
  160. case eXMLErrorCannotWriteFile: return _CXML("Error: cannot write into file");
  161. case eXMLErrorBase64DataSizeIsNotMultipleOf4: return _CXML("Warning: Base64-string length is not a multiple of 4");
  162. case eXMLErrorBase64DecodeTruncatedData: return _CXML("Warning: Base64-string is truncated");
  163. case eXMLErrorBase64DecodeIllegalCharacter: return _CXML("Error: Base64-string contains an illegal character");
  164. case eXMLErrorBase64DecodeBufferTooSmall: return _CXML("Error: Base64 decode output buffer is too small");
  165. };
  166. return _CXML("Unknown");
  167. }
  168. /////////////////////////////////////////////////////////////////////////
  169. // Here start the abstraction layer to be OS-independent //
  170. /////////////////////////////////////////////////////////////////////////
  171. // Here is an abstraction layer to access some common string manipulation functions.
  172. // The abstraction layer is currently working for gcc, Microsoft Visual Studio 6.0,
  173. // Microsoft Visual Studio .NET, CC (sun compiler) and Borland C++.
  174. // If you plan to "port" the library to a new system/compiler, all you have to do is
  175. // to edit the following lines.
  176. #ifdef XML_NO_WIDE_CHAR
  177. char myIsTextWideChar(const void *b, int len) { return FALSE; }
  178. #else
  179. #if defined (UNDER_CE) || !defined(_XMLWINDOWS)
  180. char myIsTextWideChar(const void *b, int len) // inspired by the Wine API: RtlIsTextUnicode
  181. {
  182. #ifdef sun
  183. // for SPARC processors: wchar_t* buffers must always be alligned, otherwise it's a char* buffer.
  184. if ((((unsigned long)b)%sizeof(wchar_t))!=0) return FALSE;
  185. #endif
  186. const wchar_t *s=(const wchar_t*)b;
  187. // buffer too small:
  188. if (len<(int)sizeof(wchar_t)) return FALSE;
  189. // odd length test
  190. if (len&1) return FALSE;
  191. /* only checks the first 256 characters */
  192. len=mmin(256,len/sizeof(wchar_t));
  193. // Check for the special byte order:
  194. if (*((unsigned short*)s) == 0xFFFE) return TRUE; // IS_TEXT_UNICODE_REVERSE_SIGNATURE;
  195. if (*((unsigned short*)s) == 0xFEFF) return TRUE; // IS_TEXT_UNICODE_SIGNATURE
  196. // checks for ASCII characters in the UNICODE stream
  197. int i,stats=0;
  198. for (i=0; i<len; i++) if (s[i]<=(unsigned short)255) stats++;
  199. if (stats>len/2) return TRUE;
  200. // Check for UNICODE NULL chars
  201. for (i=0; i<len; i++) if (!s[i]) return TRUE;
  202. return FALSE;
  203. }
  204. #else
  205. char myIsTextWideChar(const void *b,int l) { return (char)IsTextUnicode((CONST LPVOID)b,l,NULL); };
  206. #endif
  207. #endif
  208. #ifdef _XMLWINDOWS
  209. // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0
  210. #ifdef _XMLWIDECHAR
  211. wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce)
  212. {
  213. int i;
  214. if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,-1,NULL,0);
  215. else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,NULL,0);
  216. if (i<0) return NULL;
  217. wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(XMLCHAR));
  218. if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,-1,d,i);
  219. else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,d,i);
  220. d[i]=0;
  221. return d;
  222. }
  223. static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return _wfopen(filename,mode); }
  224. static inline int xstrlen(XMLCSTR c) { return (int)wcslen(c); }
  225. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _wcsnicmp(c1,c2,l);}
  226. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);}
  227. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _wcsicmp(c1,c2); }
  228. static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
  229. static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
  230. #else
  231. char *myWideCharToMultiByte(const wchar_t *s)
  232. {
  233. UINT codePage=CP_ACP; if (characterEncoding==XMLNode::char_encoding_UTF8) codePage=CP_UTF8;
  234. int i=(int)WideCharToMultiByte(codePage, // code page
  235. 0, // performance and mapping flags
  236. s, // wide-character string
  237. -1, // number of chars in string
  238. NULL, // buffer for new string
  239. 0, // size of buffer
  240. NULL, // default for unmappable chars
  241. NULL // set when default char used
  242. );
  243. if (i<0) return NULL;
  244. char *d=(char*)malloc(i+1);
  245. WideCharToMultiByte(codePage, // code page
  246. 0, // performance and mapping flags
  247. s, // wide-character string
  248. -1, // number of chars in string
  249. d, // buffer for new string
  250. i, // size of buffer
  251. NULL, // default for unmappable chars
  252. NULL // set when default char used
  253. );
  254. d[i]=0;
  255. return d;
  256. }
  257. static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
  258. static inline int xstrlen(XMLCSTR c) { return (int)strlen(c); }
  259. #ifdef __BORLANDC__
  260. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strnicmp(c1,c2,l);}
  261. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return stricmp(c1,c2); }
  262. #else
  263. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _strnicmp(c1,c2,l);}
  264. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _stricmp(c1,c2); }
  265. #endif
  266. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);}
  267. static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
  268. static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
  269. #endif
  270. #else
  271. // for gcc and CC
  272. #ifdef XML_NO_WIDE_CHAR
  273. char *myWideCharToMultiByte(const wchar_t *s) { return NULL; }
  274. #else
  275. char *myWideCharToMultiByte(const wchar_t *s)
  276. {
  277. const wchar_t *ss=s;
  278. int i=(int)wcsrtombs(NULL,&ss,0,NULL);
  279. if (i<0) return NULL;
  280. char *d=(char *)malloc(i+1);
  281. wcsrtombs(d,&s,i,NULL);
  282. d[i]=0;
  283. return d;
  284. }
  285. #endif
  286. #ifdef _XMLWIDECHAR
  287. wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce)
  288. {
  289. const char *ss=s;
  290. int i=(int)mbsrtowcs(NULL,&ss,0,NULL);
  291. if (i<0) return NULL;
  292. wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(wchar_t));
  293. mbsrtowcs(d,&s,i,NULL);
  294. d[i]=0;
  295. return d;
  296. }
  297. int xstrlen(XMLCSTR c) { return wcslen(c); }
  298. #ifdef sun
  299. // for CC
  300. #include <widec.h>
  301. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncasecmp(c1,c2,l);}
  302. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncmp(c1,c2,l);}
  303. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wscasecmp(c1,c2); }
  304. #else
  305. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);}
  306. #ifdef __linux__
  307. // for gcc/linux
  308. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncasecmp(c1,c2,l);}
  309. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wcscasecmp(c1,c2); }
  310. #else
  311. #include <wctype.h>
  312. // for gcc/non-linux (MacOS X 10.3, FreeBSD 6.0, NetBSD 3.0, OpenBSD 3.8, AIX 4.3.2, HP-UX 11, IRIX 6.5, OSF/1 5.1, Cygwin, mingw)
  313. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2)
  314. {
  315. wchar_t left,right;
  316. do
  317. {
  318. left=towlower(*c1++); right=towlower(*c2++);
  319. } while (left&&(left==right));
  320. return (int)left-(int)right;
  321. }
  322. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l)
  323. {
  324. wchar_t left,right;
  325. while(l--)
  326. {
  327. left=towlower(*c1++); right=towlower(*c2++);
  328. if ((!left)||(left!=right)) return (int)left-(int)right;
  329. }
  330. return 0;
  331. }
  332. #endif
  333. #endif
  334. static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
  335. static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
  336. static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode)
  337. {
  338. char *filenameAscii=myWideCharToMultiByte(filename);
  339. FILE *f;
  340. if (mode[0]==_CXML('r')) f=fopen(filenameAscii,"rb");
  341. else f=fopen(filenameAscii,"wb");
  342. free(filenameAscii);
  343. return f;
  344. }
  345. #else
  346. static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
  347. static inline int xstrlen(XMLCSTR c) { return strlen(c); }
  348. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncasecmp(c1,c2,l);}
  349. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);}
  350. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return strcasecmp(c1,c2); }
  351. static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
  352. static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
  353. #endif
  354. static inline int _strnicmp(const char *c1,const char *c2, int l) { return strncasecmp(c1,c2,l);}
  355. #endif
  356. ///////////////////////////////////////////////////////////////////////////////
  357. // the "xmltoc,xmltob,xmltoi,xmltol,xmltof,xmltoa" functions //
  358. ///////////////////////////////////////////////////////////////////////////////
  359. // These 6 functions are not used inside the XMLparser.
  360. // There are only here as "convenience" functions for the user.
  361. // If you don't need them, you can delete them without any trouble.
  362. #ifdef _XMLWIDECHAR
  363. #ifdef _XMLWINDOWS
  364. // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0
  365. char xmltob(XMLCSTR t,int v){ if (t&&(*t)) return (char)_wtoi(t); return v; }
  366. int xmltoi(XMLCSTR t,int v){ if (t&&(*t)) return _wtoi(t); return v; }
  367. long xmltol(XMLCSTR t,long v){ if (t&&(*t)) return _wtol(t); return v; }
  368. double xmltof(XMLCSTR t,double v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; }
  369. #else
  370. #ifdef sun
  371. // for CC
  372. #include <widec.h>
  373. char xmltob(XMLCSTR t,int v){ if (t) return (char)wstol(t,NULL,10); return v; }
  374. int xmltoi(XMLCSTR t,int v){ if (t) return (int)wstol(t,NULL,10); return v; }
  375. long xmltol(XMLCSTR t,long v){ if (t) return wstol(t,NULL,10); return v; }
  376. #else
  377. // for gcc
  378. char xmltob(XMLCSTR t,int v){ if (t) return (char)wcstol(t,NULL,10); return v; }
  379. int xmltoi(XMLCSTR t,int v){ if (t) return (int)wcstol(t,NULL,10); return v; }
  380. long xmltol(XMLCSTR t,long v){ if (t) return wcstol(t,NULL,10); return v; }
  381. #endif
  382. double xmltof(XMLCSTR t,double v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; }
  383. #endif
  384. #else
  385. char xmltob(XMLCSTR t,char v){ if (t&&(*t)) return (char)atoi(t); return v; }
  386. int xmltoi(XMLCSTR t,int v){ if (t&&(*t)) return atoi(t); return v; }
  387. long xmltol(XMLCSTR t,long v){ if (t&&(*t)) return atol(t); return v; }
  388. double xmltof(XMLCSTR t,double v){ if (t&&(*t)) return atof(t); return v; }
  389. #endif
  390. XMLCSTR xmltoa(XMLCSTR t,XMLCSTR v){ if (t) return t; return v; }
  391. XMLCHAR xmltoc(XMLCSTR t,const XMLCHAR v){ if (t&&(*t)) return *t; return v; }
  392. /////////////////////////////////////////////////////////////////////////
  393. // the "openFileHelper" function //
  394. /////////////////////////////////////////////////////////////////////////
  395. // Since each application has its own way to report and deal with errors, you should modify & rewrite
  396. // the following "openFileHelper" function to get an "error reporting mechanism" tailored to your needs.
  397. XMLNode XMLNode::openFileHelper(XMLCSTR filename, XMLCSTR tag)
  398. {
  399. // guess the value of the global parameter "characterEncoding"
  400. // (the guess is based on the first 200 bytes of the file).
  401. FILE *f=xfopen(filename,_CXML("rb"));
  402. if (f)
  403. {
  404. char bb[205];
  405. int l=(int)fread(bb,1,200,f);
  406. setGlobalOptions(guessCharEncoding(bb,l),guessWideCharChars,dropWhiteSpace,removeCommentsInMiddleOfText);
  407. fclose(f);
  408. }
  409. // parse the file
  410. XMLResults pResults;
  411. XMLNode xnode=XMLNode::parseFile(filename,tag,&pResults);
  412. // display error message (if any)
  413. if (pResults.error != eXMLErrorNone)
  414. {
  415. // create message
  416. char message[2000],*s1=(char*)"",*s3=(char*)""; XMLCSTR s2=_CXML("");
  417. if (pResults.error==eXMLErrorFirstTagNotFound) { s1=(char*)"First Tag should be '"; s2=tag; s3=(char*)"'.\n"; }
  418. sprintf(message,
  419. #ifdef _XMLWIDECHAR
  420. "XML Parsing error inside file '%S'.\n%S\nAt line %i, column %i.\n%s%S%s"
  421. #else
  422. "XML Parsing error inside file '%s'.\n%s\nAt line %i, column %i.\n%s%s%s"
  423. #endif
  424. ,filename,XMLNode::getError(pResults.error),pResults.nLine,pResults.nColumn,s1,s2,s3);
  425. // display message
  426. #if defined(_XMLWINDOWS) && !defined(UNDER_CE) && !defined(_XMLPARSER_NO_MESSAGEBOX_)
  427. MessageBoxA(NULL,message,"XML Parsing error",MB_OK|MB_ICONERROR|MB_TOPMOST);
  428. #else
  429. printf("%s",message);
  430. #endif
  431. exit(255);
  432. }
  433. return xnode;
  434. }
  435. /////////////////////////////////////////////////////////////////////////
  436. // Here start the core implementation of the XMLParser library //
  437. /////////////////////////////////////////////////////////////////////////
  438. // You should normally not change anything below this point.
  439. #ifndef _XMLWIDECHAR
  440. // If "characterEncoding=ascii" then we assume that all characters have the same length of 1 byte.
  441. // If "characterEncoding=UTF8" then the characters have different lengths (from 1 byte to 4 bytes).
  442. // If "characterEncoding=ShiftJIS" then the characters have different lengths (from 1 byte to 2 bytes).
  443. // This table is used as lookup-table to know the length of a character (in byte) based on the
  444. // content of the first byte of the character.
  445. // (note: if you modify this, you must always have XML_utf8ByteTable[0]=0 ).
  446. static const char XML_utf8ByteTable[256] =
  447. {
  448. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  449. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  450. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  451. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  452. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  453. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  454. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  455. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  456. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70 End of ASCII range
  457. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 0x80 to 0xc1 invalid
  458. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
  459. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
  460. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
  461. 1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 0xc2 to 0xdf 2 byte
  462. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  463. 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,// 0xe0 0xe0 to 0xef 3 byte
  464. 4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid
  465. };
  466. static const char XML_legacyByteTable[256] =
  467. {
  468. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  469. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  470. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  471. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  472. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  473. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  474. };
  475. static const char XML_sjisByteTable[256] =
  476. {
  477. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  478. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  479. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  480. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  481. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  482. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  483. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  484. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  485. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
  486. 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0x9F 2 bytes
  487. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
  488. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
  489. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
  490. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xc0
  491. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xd0
  492. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0 0xe0 to 0xef 2 bytes
  493. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 // 0xf0
  494. };
  495. static const char XML_gb2312ByteTable[256] =
  496. {
  497. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  498. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  499. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  500. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  501. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  502. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  503. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  504. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  505. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
  506. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80
  507. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
  508. 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0 0xa1 to 0xf7 2 bytes
  509. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
  510. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
  511. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  512. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
  513. 2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1 // 0xf0
  514. };
  515. static const char XML_gbk_big5_ByteTable[256] =
  516. {
  517. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  518. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  519. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  520. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  521. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  522. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  523. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  524. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  525. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
  526. 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0xfe 2 bytes
  527. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
  528. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0
  529. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
  530. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
  531. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  532. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
  533. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1 // 0xf0
  534. };
  535. static const char *XML_ByteTable=(const char *)XML_utf8ByteTable; // the default is "characterEncoding=XMLNode::encoding_UTF8"
  536. #endif
  537. XMLNode XMLNode::emptyXMLNode;
  538. XMLClear XMLNode::emptyXMLClear={ NULL, NULL, NULL};
  539. XMLAttribute XMLNode::emptyXMLAttribute={ NULL, NULL};
  540. // Enumeration used to decipher what type a token is
  541. typedef enum XMLTokenTypeTag
  542. {
  543. eTokenText = 0,
  544. eTokenQuotedText,
  545. eTokenTagStart, /* "<" */
  546. eTokenTagEnd, /* "</" */
  547. eTokenCloseTag, /* ">" */
  548. eTokenEquals, /* "=" */
  549. eTokenDeclaration, /* "<?" */
  550. eTokenShortHandClose, /* "/>" */
  551. eTokenClear,
  552. eTokenError
  553. } XMLTokenType;
  554. // Main structure used for parsing XML
  555. typedef struct XML
  556. {
  557. XMLCSTR lpXML;
  558. XMLCSTR lpszText;
  559. int nIndex,nIndexMissigEndTag;
  560. enum XMLError error;
  561. XMLCSTR lpEndTag;
  562. int cbEndTag;
  563. XMLCSTR lpNewElement;
  564. int cbNewElement;
  565. int nFirst;
  566. } XML;
  567. typedef struct
  568. {
  569. ALLXMLClearTag *pClr;
  570. XMLCSTR pStr;
  571. } NextToken;
  572. // Enumeration used when parsing attributes
  573. typedef enum Attrib
  574. {
  575. eAttribName = 0,
  576. eAttribEquals,
  577. eAttribValue
  578. } Attrib;
  579. // Enumeration used when parsing elements to dictate whether we are currently
  580. // inside a tag
  581. typedef enum Status
  582. {
  583. eInsideTag = 0,
  584. eOutsideTag
  585. } Status;
  586. XMLError XMLNode::writeToFile(XMLCSTR filename, const char *encoding, char nFormat) const
  587. {
  588. if (!d) return eXMLErrorNone;
  589. FILE *f=xfopen(filename,_CXML("wb"));
  590. if (!f) return eXMLErrorCannotOpenWriteFile;
  591. #ifdef _XMLWIDECHAR
  592. unsigned char h[2]={ 0xFF, 0xFE };
  593. if (!fwrite(h,2,1,f)) return eXMLErrorCannotWriteFile;
  594. if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
  595. {
  596. if (!fwrite(L"<?xml version=\"1.0\" encoding=\"utf-16\"?>\n",sizeof(wchar_t)*40,1,f))
  597. return eXMLErrorCannotWriteFile;
  598. }
  599. #else
  600. if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
  601. {
  602. if (characterEncoding==char_encoding_UTF8)
  603. {
  604. // header so that windows recognize the file as UTF-8:
  605. unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
  606. encoding="utf-8";
  607. } else if (characterEncoding==char_encoding_ShiftJIS) encoding="SHIFT-JIS";
  608. if (!encoding) encoding="ISO-8859-1";
  609. if (fprintf(f,"<?xml version=\"1.0\" encoding=\"%s\"?>\n",encoding)<0) return eXMLErrorCannotWriteFile;
  610. } else
  611. {
  612. if (characterEncoding==char_encoding_UTF8)
  613. {
  614. unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
  615. }
  616. }
  617. #endif
  618. int i;
  619. XMLSTR t=createXMLString(nFormat,&i);
  620. if (!fwrite(t,sizeof(XMLCHAR)*i,1,f)) return eXMLErrorCannotWriteFile;
  621. if (fclose(f)!=0) return eXMLErrorCannotWriteFile;
  622. free(t);
  623. return eXMLErrorNone;
  624. }
  625. // Duplicate a given string.
  626. XMLSTR stringDup(XMLCSTR lpszData, int cbData)
  627. {
  628. if (lpszData==NULL) return NULL;
  629. XMLSTR lpszNew;
  630. if (cbData==-1) cbData=(int)xstrlen(lpszData);
  631. lpszNew = (XMLSTR)malloc((cbData+1) * sizeof(XMLCHAR));
  632. if (lpszNew)
  633. {
  634. memcpy(lpszNew, lpszData, (cbData) * sizeof(XMLCHAR));
  635. lpszNew[cbData] = (XMLCHAR)NULL;
  636. }
  637. return lpszNew;
  638. }
  639. XMLSTR ToXMLStringTool::toXMLUnSafe(XMLSTR dest,XMLCSTR source)
  640. {
  641. XMLSTR dd=dest;
  642. XMLCHAR ch;
  643. XMLCharacterEntity *entity;
  644. while ((ch=*source))
  645. {
  646. entity=XMLEntities;
  647. do
  648. {
  649. if (ch==entity->c) {xstrcpy(dest,entity->s); dest+=entity->l; source++; goto out_of_loop1; }
  650. entity++;
  651. } while(entity->s);
  652. #ifdef _XMLWIDECHAR
  653. *(dest++)=*(source++);
  654. #else
  655. switch(XML_ByteTable[(unsigned char)ch])
  656. {
  657. case 4: *(dest++)=*(source++);
  658. case 3: *(dest++)=*(source++);
  659. case 2: *(dest++)=*(source++);
  660. case 1: *(dest++)=*(source++);
  661. }
  662. #endif
  663. out_of_loop1:
  664. ;
  665. }
  666. *dest=0;
  667. return dd;
  668. }
  669. // private (used while rendering):
  670. int ToXMLStringTool::lengthXMLString(XMLCSTR source)
  671. {
  672. int r=0;
  673. XMLCharacterEntity *entity;
  674. XMLCHAR ch;
  675. while ((ch=*source))
  676. {
  677. entity=XMLEntities;
  678. do
  679. {
  680. if (ch==entity->c) { r+=entity->l; source++; goto out_of_loop1; }
  681. entity++;
  682. } while(entity->s);
  683. #ifdef _XMLWIDECHAR
  684. r++; source++;
  685. #else
  686. ch=XML_ByteTable[(unsigned char)ch]; r+=ch; source+=ch;
  687. #endif
  688. out_of_loop1:
  689. ;
  690. }
  691. return r;
  692. }
  693. ToXMLStringTool::~ToXMLStringTool(){ freeBuffer(); }
  694. void ToXMLStringTool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; }
  695. XMLSTR ToXMLStringTool::toXML(XMLCSTR source)
  696. {
  697. if (!source) return _CXML("");
  698. int l=lengthXMLString(source)+1;
  699. if (l>buflen) { buflen=l; buf=(XMLSTR)realloc(buf,l*sizeof(XMLCHAR)); }
  700. return toXMLUnSafe(buf,source);
  701. }
  702. // private:
  703. XMLSTR fromXMLString(XMLCSTR s, int lo, XML *pXML)
  704. {
  705. // This function is the opposite of the function "toXMLString". It decodes the escape
  706. // sequences &amp;, &quot;, &apos;, &lt;, &gt; and replace them by the characters
  707. // &,",',<,>. This function is used internally by the XML Parser. All the calls to
  708. // the XML library will always gives you back "decoded" strings.
  709. //
  710. // in: string (s) and length (lo) of string
  711. // out: new allocated string converted from xml
  712. if (!s) return NULL;
  713. int ll=0,j;
  714. XMLSTR d;
  715. XMLCSTR ss=s;
  716. XMLCharacterEntity *entity;
  717. while ((lo>0)&&(*s))
  718. {
  719. if (*s==_CXML('&'))
  720. {
  721. if ((lo>2)&&(s[1]==_CXML('#')))
  722. {
  723. s+=2; lo-=2;
  724. if ((*s==_CXML('X'))||(*s==_CXML('x'))) { s++; lo--; }
  725. while ((*s)&&(*s!=_CXML(';'))&&((lo--)>0)) s++;
  726. if (*s!=_CXML(';'))
  727. {
  728. pXML->error=eXMLErrorUnknownCharacterEntity;
  729. return NULL;
  730. }
  731. s++; lo--;
  732. } else
  733. {
  734. entity=XMLEntities;
  735. do
  736. {
  737. if ((lo>=entity->l)&&(xstrnicmp(s,entity->s,entity->l)==0)) { s+=entity->l; lo-=entity->l; break; }
  738. entity++;
  739. } while(entity->s);
  740. if (!entity->s)
  741. {
  742. pXML->error=eXMLErrorUnknownCharacterEntity;
  743. return NULL;
  744. }
  745. }
  746. } else
  747. {
  748. #ifdef _XMLWIDECHAR
  749. s++; lo--;
  750. #else
  751. j=XML_ByteTable[(unsigned char)*s]; s+=j; lo-=j; ll+=j-1;
  752. #endif
  753. }
  754. ll++;
  755. }
  756. d=(XMLSTR)malloc((ll+1)*sizeof(XMLCHAR));
  757. s=d;
  758. while (ll-->0)
  759. {
  760. if (*ss==_CXML('&'))
  761. {
  762. if (ss[1]==_CXML('#'))
  763. {
  764. ss+=2; j=0;
  765. if ((*ss==_CXML('X'))||(*ss==_CXML('x')))
  766. {
  767. ss++;
  768. while (*ss!=_CXML(';'))
  769. {
  770. if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j<<4)+*ss-_CXML('0');
  771. else if ((*ss>=_CXML('A'))&&(*ss<=_CXML('F'))) j=(j<<4)+*ss-_CXML('A')+10;
  772. else if ((*ss>=_CXML('a'))&&(*ss<=_CXML('f'))) j=(j<<4)+*ss-_CXML('a')+10;
  773. else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
  774. ss++;
  775. }
  776. } else
  777. {
  778. while (*ss!=_CXML(';'))
  779. {
  780. if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j*10)+*ss-_CXML('0');
  781. else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
  782. ss++;
  783. }
  784. }
  785. #ifndef _XMLWIDECHAR
  786. if (j>255) { free((void*)s); pXML->error=eXMLErrorCharacterCodeAbove255;return NULL;}
  787. #endif
  788. (*d++)=(XMLCHAR)j; ss++;
  789. } else
  790. {
  791. entity=XMLEntities;
  792. do
  793. {
  794. if (xstrnicmp(ss,entity->s,entity->l)==0) { *(d++)=entity->c; ss+=entity->l; break; }
  795. entity++;
  796. } while(entity->s);
  797. }
  798. } else
  799. {
  800. #ifdef _XMLWIDECHAR
  801. *(d++)=*(ss++);
  802. #else
  803. switch(XML_ByteTable[(unsigned char)*ss])
  804. {
  805. case 4: *(d++)=*(ss++); ll--;
  806. case 3: *(d++)=*(ss++); ll--;
  807. case 2: *(d++)=*(ss++); ll--;
  808. case 1: *(d++)=*(ss++);
  809. }
  810. #endif
  811. }
  812. }
  813. *d=0;
  814. return (XMLSTR)s;
  815. }
  816. #define XML_isSPACECHAR(ch) ((ch==_CXML('\n'))||(ch==_CXML(' '))||(ch== _CXML('\t'))||(ch==_CXML('\r')))
  817. // private:
  818. char myTagCompare(XMLCSTR cclose, XMLCSTR copen)
  819. // !!!! WARNING strange convention&:
  820. // return 0 if equals
  821. // return 1 if different
  822. {
  823. if (!cclose) return 1;
  824. int l=(int)xstrlen(cclose);
  825. if (xstrnicmp(cclose, copen, l)!=0) return 1;
  826. const XMLCHAR c=copen[l];
  827. if (XML_isSPACECHAR(c)||
  828. (c==_CXML('/' ))||
  829. (c==_CXML('<' ))||
  830. (c==_CXML('>' ))||
  831. (c==_CXML('=' ))) return 0;
  832. return 1;
  833. }
  834. // Obtain the next character from the string.
  835. static inline XMLCHAR getNextChar(XML *pXML)
  836. {
  837. XMLCHAR ch = pXML->lpXML[pXML->nIndex];
  838. #ifdef _XMLWIDECHAR
  839. if (ch!=0) pXML->nIndex++;
  840. #else
  841. pXML->nIndex+=XML_ByteTable[(unsigned char)ch];
  842. #endif
  843. return ch;
  844. }
  845. // Find the next token in a string.
  846. // pcbToken contains the number of characters that have been read.
  847. static NextToken GetNextToken(XML *pXML, int *pcbToken, enum XMLTokenTypeTag *pType)
  848. {
  849. NextToken result;
  850. XMLCHAR ch;
  851. XMLCHAR chTemp;
  852. int indexStart,nFoundMatch,nIsText=FALSE;
  853. result.pClr=NULL; // prevent warning
  854. // Find next non-white space character
  855. do { indexStart=pXML->nIndex; ch=getNextChar(pXML); } while XML_isSPACECHAR(ch);
  856. if (ch)
  857. {
  858. // Cache the current string pointer
  859. result.pStr = &pXML->lpXML[indexStart];
  860. // First check whether the token is in the clear tag list (meaning it
  861. // does not need formatting).
  862. ALLXMLClearTag *ctag=XMLClearTags;
  863. do
  864. {
  865. if (xstrncmp(ctag->lpszOpen, result.pStr, ctag->openTagLen)==0)
  866. {
  867. result.pClr=ctag;
  868. pXML->nIndex+=ctag->openTagLen-1;
  869. *pType=eTokenClear;
  870. return result;
  871. }
  872. ctag++;
  873. } while(ctag->lpszOpen);
  874. // If we didn't find a clear tag then check for standard tokens
  875. switch(ch)
  876. {
  877. // Check for quotes
  878. case _CXML('\''):
  879. case _CXML('\"'):
  880. // Type of token
  881. *pType = eTokenQuotedText;
  882. chTemp = ch;
  883. // Set the size
  884. nFoundMatch = FALSE;
  885. // Search through the string to find a matching quote
  886. while((ch = getNextChar(pXML)))
  887. {
  888. if (ch==chTemp) { nFoundMatch = TRUE; break; }
  889. if (ch==_CXML('<')) break;
  890. }
  891. // If we failed to find a matching quote
  892. if (nFoundMatch == FALSE)
  893. {
  894. pXML->nIndex=indexStart+1;
  895. nIsText=TRUE;
  896. break;
  897. }
  898. // 4.02.2002
  899. // if (FindNonWhiteSpace(pXML)) pXML->nIndex--;
  900. break;
  901. // Equals (used with attribute values)
  902. case _CXML('='):
  903. *pType = eTokenEquals;
  904. break;
  905. // Close tag
  906. case _CXML('>'):
  907. *pType = eTokenCloseTag;
  908. break;
  909. // Check for tag start and tag end
  910. case _CXML('<'):
  911. // Peek at the next character to see if we have an end tag '</',
  912. // or an xml declaration '<?'
  913. chTemp = pXML->lpXML[pXML->nIndex];
  914. // If we have a tag end...
  915. if (chTemp == _CXML('/'))
  916. {
  917. // Set the type and ensure we point at the next character
  918. getNextChar(pXML);
  919. *pType = eTokenTagEnd;
  920. }
  921. // If we have an XML declaration tag
  922. else if (chTemp == _CXML('?'))
  923. {
  924. // Set the type and ensure we point at the next character
  925. getNextChar(pXML);
  926. *pType = eTokenDeclaration;
  927. }
  928. // Otherwise we must have a start tag
  929. else
  930. {
  931. *pType = eTokenTagStart;
  932. }
  933. break;
  934. // Check to see if we have a short hand type end tag ('/>').
  935. case _CXML('/'):
  936. // Peek at the next character to see if we have a short end tag '/>'
  937. chTemp = pXML->lpXML[pXML->nIndex];
  938. // If we have a short hand end tag...
  939. if (chTemp == _CXML('>'))
  940. {
  941. // Set the type and ensure we point at the next character
  942. getNextChar(pXML);
  943. *pType = eTokenShortHandClose;
  944. break;
  945. }
  946. // If we haven't found a short hand closing tag then drop into the
  947. // text process
  948. // Other characters
  949. default:
  950. nIsText = TRUE;
  951. }
  952. // If this is a TEXT node
  953. if (nIsText)
  954. {
  955. // Indicate we are dealing with text
  956. *pType = eTokenText;
  957. while((ch = getNextChar(pXML)))
  958. {
  959. if XML_isSPACECHAR(ch)
  960. {
  961. indexStart++; break;
  962. } else if (ch==_CXML('/'))
  963. {
  964. // If we find a slash then this maybe text or a short hand end tag
  965. // Peek at the next character to see it we have short hand end tag
  966. ch=pXML->lpXML[pXML->nIndex];
  967. // If we found a short hand end tag then we need to exit the loop
  968. if (ch==_CXML('>')) { pXML->nIndex--; break; }
  969. } else if ((ch==_CXML('<'))||(ch==_CXML('>'))||(ch==_CXML('=')))
  970. {
  971. pXML->nIndex--; break;
  972. }
  973. }
  974. }
  975. *pcbToken = pXML->nIndex-indexStart;
  976. } else
  977. {
  978. // If we failed to obtain a valid character
  979. *pcbToken = 0;
  980. *pType = eTokenError;
  981. result.pStr=NULL;
  982. }
  983. return result;
  984. }
  985. XMLCSTR XMLNode::updateName_WOSD(XMLSTR lpszName)
  986. {
  987. if (!d) { free(lpszName); return NULL; }
  988. if (d->lpszName&&(lpszName!=d->lpszName)) free((void*)d->lpszName);
  989. d->lpszName=lpszName;
  990. return lpszName;
  991. }
  992. // private:
  993. XMLNode::XMLNode(struct XMLNodeDataTag *p){ d=p; (p->ref_count)++; }
  994. XMLNode::XMLNode(XMLNodeData *pParent, XMLSTR lpszName, char isDeclaration)
  995. {
  996. d=(XMLNodeData*)malloc(sizeof(XMLNodeData));
  997. d->ref_count=1;
  998. d->lpszName=NULL;
  999. d->nChild= 0;
  1000. d->nText = 0;
  1001. d->nClear = 0;
  1002. d->nAttribute = 0;
  1003. d->isDeclaration = isDeclaration;
  1004. d->pParent = pParent;
  1005. d->pChild= NULL;
  1006. d->pText= NULL;
  1007. d->pClear= NULL;
  1008. d->pAttribute= NULL;
  1009. d->pOrder= NULL;
  1010. updateName_WOSD(lpszName);
  1011. }
  1012. XMLNode XMLNode::createXMLTopNode_WOSD(XMLSTR lpszName, char isDeclaration) { return XMLNode(NULL,lpszName,isDeclaration); }
  1013. XMLNode XMLNode::createXMLTopNode(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,stringDup(lpszName),isDeclaration); }
  1014. #define MEMORYINCREASE 50
  1015. static inline void myFree(void *p) { if (p) free(p); }
  1016. static inline void *myRealloc(void *p, int newsize, int memInc, int sizeofElem)
  1017. {
  1018. if (p==NULL) { if (memInc) return malloc(memInc*sizeofElem); return malloc(sizeofElem); }
  1019. if ((memInc==0)||((newsize%memInc)==0)) p=realloc(p,(newsize+memInc)*sizeofElem);
  1020. // if (!p)
  1021. // {
  1022. // printf("XMLParser Error: Not enough memory! Aborting...\n"); exit(220);
  1023. // }
  1024. return p;
  1025. }
  1026. // private:
  1027. XMLElementPosition XMLNode::findPosition(XMLNodeData *d, int index, XMLElementType xxtype)
  1028. {
  1029. if (index<0) return -1;
  1030. int i=0,j=(int)((index<<2)+xxtype),*o=d->pOrder; while (o[i]!=j) i++; return i;
  1031. }
  1032. // private:
  1033. // update "order" information when deleting a content of a XMLNode
  1034. int XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index)
  1035. {
  1036. int n=d->nChild+d->nText+d->nClear, *o=d->pOrder,i=findPosition(d,index,t);
  1037. memmove(o+i, o+i+1, (n-i)*sizeof(int));
  1038. for (;i<n;i++)
  1039. if ((o[i]&3)==(int)t) o[i]-=4;
  1040. // We should normally do:
  1041. // d->pOrder=(int)realloc(d->pOrder,n*sizeof(int));
  1042. // but we skip reallocation because it's too time consuming.
  1043. // Anyway, at the end, it will be free'd completely at once.
  1044. return i;
  1045. }
  1046. void *XMLNode::addToOrder(int memoryIncrease,int *_pos, int nc, void *p, int size, XMLElementType xtype)
  1047. {
  1048. // in: *_pos is the position inside d->pOrder ("-1" means "EndOf")
  1049. // out: *_pos is the index inside p
  1050. p=myRealloc(p,(nc+1),memoryIncrease,size);
  1051. int n=d->nChild+d->nText+d->nClear;
  1052. d->pOrder=(int*)myRealloc(d->pOrder,n+1,memoryIncrease*3,sizeof(int));
  1053. int pos=*_pos,*o=d->pOrder;
  1054. if ((pos<0)||(pos>=n)) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
  1055. int i=pos;
  1056. memmove(o+i+1, o+i, (n-i)*sizeof(int));
  1057. while ((pos<n)&&((o[pos]&3)!=(int)xtype)) pos++;
  1058. if (pos==n) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
  1059. o[i]=o[pos];
  1060. for (i=pos+1;i<=n;i++) if ((o[i]&3)==(int)xtype) o[i]+=4;
  1061. *_pos=pos=o[pos]>>2;
  1062. memmove(((char*)p)+(pos+1)*size,((char*)p)+pos*size,(nc-pos)*size);
  1063. return p;
  1064. }
  1065. // Add a child node to the given element.
  1066. XMLNode XMLNode::addChild_priv(int memoryIncrease, XMLSTR lpszName, char isDeclaration, int pos)
  1067. {
  1068. if (!lpszName) return emptyXMLNode;
  1069. d->pChild=(XMLNode*)addToOrder(memoryIncrease,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
  1070. d->pChild[pos].d=NULL;
  1071. d->pChild[pos]=XMLNode(d,lpszName,isDeclaration);
  1072. d->nChild++;
  1073. return d->pChild[pos];
  1074. }
  1075. // Add an attribute to an element.
  1076. XMLAttribute *XMLNode::addAttribute_priv(int memoryIncrease,XMLSTR lpszName, XMLSTR lpszValuev)
  1077. {
  1078. if (!lpszName) return &emptyXMLAttribute;
  1079. if (!d) { myFree(lpszName); myFree(lpszValuev); return &emptyXMLAttribute; }
  1080. int nc=d->nAttribute;
  1081. d->pAttribute=(XMLAttribute*)myRealloc(d->pAttribute,(nc+1),memoryIncrease,sizeof(XMLAttribute));
  1082. XMLAttribute *pAttr=d->pAttribute+nc;
  1083. pAttr->lpszName = lpszName;
  1084. pAttr->lpszValue = lpszValuev;
  1085. d->nAttribute++;
  1086. return pAttr;
  1087. }
  1088. // Add text to the element.
  1089. XMLCSTR XMLNode::addText_priv(int memoryIncrease, XMLSTR lpszValue, int pos)
  1090. {
  1091. if (!lpszValue) return NULL;
  1092. if (!d) { myFree(lpszValue); return NULL; }
  1093. d->pText=(XMLCSTR*)addToOrder(memoryIncrease,&pos,d->nText,d->pText,sizeof(XMLSTR),eNodeText);
  1094. d->pText[pos]=lpszValue;
  1095. d->nText++;
  1096. return lpszValue;
  1097. }
  1098. // Add clear (unformatted) text to the element.
  1099. XMLClear *XMLNode::addClear_priv(int memoryIncrease, XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
  1100. {
  1101. if (!lpszValue) return &emptyXMLClear;
  1102. if (!d) { myFree(lpszValue); return &emptyXMLClear; }
  1103. d->pClear=(XMLClear *)addToOrder(memoryIncrease,&pos,d->nClear,d->pClear,sizeof(XMLClear),eNodeClear);
  1104. XMLClear *pNewClear=d->pClear+pos;
  1105. pNewClear->lpszValue = lpszValue;
  1106. if (!lpszOpen) lpszOpen=XMLClearTags->lpszOpen;
  1107. if (!lpszClose) lpszClose=XMLClearTags->lpszClose;
  1108. pNewClear->lpszOpenTag = lpszOpen;
  1109. pNewClear->lpszCloseTag = lpszClose;
  1110. d->nClear++;
  1111. return pNewClear;
  1112. }
  1113. // private:
  1114. // Parse a clear (unformatted) type node.
  1115. char XMLNode::parseClearTag(void *px, void *_pClear)
  1116. {
  1117. XML *pXML=(XML *)px;
  1118. ALLXMLClearTag pClear=*((ALLXMLClearTag*)_pClear);
  1119. int cbTemp=0;
  1120. XMLCSTR lpszTemp=NULL;
  1121. XMLCSTR lpXML=&pXML->lpXML[pXML->nIndex];
  1122. static XMLCSTR docTypeEnd=_CXML("]>");
  1123. // Find the closing tag
  1124. // Seems the <!DOCTYPE need a better treatment so lets handle it
  1125. if (pClear.lpszOpen==XMLClearTags[1].lpszOpen)
  1126. {
  1127. XMLCSTR pCh=lpXML;
  1128. while (*pCh)
  1129. {
  1130. if (*pCh==_CXML('<')) { pClear.lpszClose=docTypeEnd; lpszTemp=xstrstr(lpXML,docTypeEnd); break; }
  1131. else if (*pCh==_CXML('>')) { lpszTemp=pCh; break; }
  1132. #ifdef _XMLWIDECHAR
  1133. pCh++;
  1134. #else
  1135. pCh+=XML_ByteTable[(unsigned char)(*pCh)];
  1136. #endif
  1137. }
  1138. } else lpszTemp=xstrstr(lpXML, pClear.lpszClose);
  1139. if (lpszTemp)
  1140. {
  1141. // Cache the size and increment the index
  1142. cbTemp = (int)(lpszTemp - lpXML);
  1143. pXML->nIndex += cbTemp+(int)xstrlen(pClear.lpszClose);
  1144. // Add the clear node to the current element
  1145. addClear_priv(MEMORYINCREASE,stringDup(lpXML,cbTemp), pClear.lpszOpen, pClear.lpszClose,-1);
  1146. return 0;
  1147. }
  1148. // If we failed to find the end tag
  1149. pXML->error = eXMLErrorUnmatchedEndClearTag;
  1150. return 1;
  1151. }
  1152. void XMLNode::exactMemory(XMLNodeData *d)
  1153. {
  1154. if (d->pOrder) d->pOrder=(int*)realloc(d->pOrder,(d->nChild+d->nText+d->nClear)*sizeof(int));
  1155. if (d->pChild) d->pChild=(XMLNode*)realloc(d->pChild,d->nChild*sizeof(XMLNode));
  1156. if (d->pAttribute) d->pAttribute=(XMLAttribute*)realloc(d->pAttribute,d->nAttribute*sizeof(XMLAttribute));
  1157. if (d->pText) d->pText=(XMLCSTR*)realloc(d->pText,d->nText*sizeof(XMLSTR));
  1158. if (d->pClear) d->pClear=(XMLClear *)realloc(d->pClear,d->nClear*sizeof(XMLClear));
  1159. }
  1160. char XMLNode::maybeAddTxT(void *pa, XMLCSTR tokenPStr)
  1161. {
  1162. XML *pXML=(XML *)pa;
  1163. XMLCSTR lpszText=pXML->lpszText;
  1164. if (!lpszText) return 0;
  1165. if (dropWhiteSpace) while (XML_isSPACECHAR(*lpszText)&&(lpszText!=tokenPStr)) lpszText++;
  1166. int cbText = (int)(tokenPStr - lpszText);
  1167. if (!cbText) { pXML->lpszText=NULL; return 0; }
  1168. if (dropWhiteSpace) { cbText--; while ((cbText)&&XML_isSPACECHAR(lpszText[cbText])) cbText--; cbText++; }
  1169. if (!cbText) { pXML->lpszText=NULL; return 0; }
  1170. XMLSTR lpt=fromXMLString(lpszText,cbText,pXML);
  1171. if (!lpt) return 1;
  1172. pXML->lpszText=NULL;
  1173. if (removeCommentsInMiddleOfText && d->nText && d->nClear)
  1174. {
  1175. // if the previous insertion was a comment (<!-- -->) AND
  1176. // if the previous previous insertion was a text then, delete the comment and append the text
  1177. int n=d->nChild+d->nText+d->nClear-1,*o=d->pOrder;
  1178. if (((o[n]&3)==eNodeClear)&&((o[n-1]&3)==eNo

Large files files are truncated, but you can click here to view the full file