PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/DependentExtensions/XML/xmlParser.cpp

http://github.com/Undergarun/RakNet
C++ | 1664 lines | 1173 code | 153 blank | 338 comment | 210 complexity | 5093048ed61418fa5f7bb630bb1591c7 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 "RakNet project", including applications
  47. * using "RakNet project" and tools developed
  48. * for enhancing "RakNet project". All other projects
  49. * (not related to "RakNet 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. else
  410. {
  411. return XMLNode();
  412. }
  413. // parse the file
  414. XMLResults pResults;
  415. XMLNode xnode=XMLNode::parseFile(filename,tag,&pResults);
  416. // display error message (if any)
  417. if (pResults.error != eXMLErrorNone)
  418. {
  419. // create message
  420. char message[2000],*s1=(char*)"",*s3=(char*)""; XMLCSTR s2=_CXML("");
  421. if (pResults.error==eXMLErrorFirstTagNotFound) { s1=(char*)"First Tag should be '"; s2=tag; s3=(char*)"'.\n"; }
  422. sprintf(message,
  423. #ifdef _XMLWIDECHAR
  424. "XML Parsing error inside file '%S'.\n%S\nAt line %i, column %i.\n%s%S%s"
  425. #else
  426. "XML Parsing error inside file '%s'.\n%s\nAt line %i, column %i.\n%s%s%s"
  427. #endif
  428. ,filename,XMLNode::getError(pResults.error),pResults.nLine,pResults.nColumn,s1,s2,s3);
  429. // display message
  430. #if defined(_XMLWINDOWS) && !defined(UNDER_CE) && !defined(_XMLPARSER_NO_MESSAGEBOX_)
  431. MessageBoxA(NULL,message,"XML Parsing error",MB_OK|MB_ICONERROR|MB_TOPMOST);
  432. #else
  433. printf("%s",message);
  434. #endif
  435. exit(255);
  436. }
  437. return xnode;
  438. }
  439. /////////////////////////////////////////////////////////////////////////
  440. // Here start the core implementation of the XMLParser library //
  441. /////////////////////////////////////////////////////////////////////////
  442. // You should normally not change anything below this point.
  443. #ifndef _XMLWIDECHAR
  444. // If "characterEncoding=ascii" then we assume that all characters have the same length of 1 byte.
  445. // If "characterEncoding=UTF8" then the characters have different lengths (from 1 byte to 4 bytes).
  446. // If "characterEncoding=ShiftJIS" then the characters have different lengths (from 1 byte to 2 bytes).
  447. // This table is used as lookup-table to know the length of a character (in byte) based on the
  448. // content of the first byte of the character.
  449. // (note: if you modify this, you must always have XML_utf8ByteTable[0]=0 ).
  450. static const char XML_utf8ByteTable[256] =
  451. {
  452. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  453. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  454. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  455. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  456. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  457. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  458. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  459. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  460. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70 End of ASCII range
  461. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 0x80 to 0xc1 invalid
  462. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
  463. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
  464. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
  465. 1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 0xc2 to 0xdf 2 byte
  466. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  467. 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,// 0xe0 0xe0 to 0xef 3 byte
  468. 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
  469. };
  470. static const char XML_legacyByteTable[256] =
  471. {
  472. 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,
  473. 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,
  474. 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,
  475. 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,
  476. 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,
  477. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  478. };
  479. static const char XML_sjisByteTable[256] =
  480. {
  481. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  482. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  483. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  484. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  485. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  486. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  487. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  488. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  489. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
  490. 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0x9F 2 bytes
  491. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
  492. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
  493. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
  494. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xc0
  495. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xd0
  496. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0 0xe0 to 0xef 2 bytes
  497. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 // 0xf0
  498. };
  499. static const char XML_gb2312ByteTable[256] =
  500. {
  501. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  502. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  503. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  504. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  505. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  506. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  507. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  508. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  509. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
  510. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80
  511. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
  512. 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0 0xa1 to 0xf7 2 bytes
  513. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
  514. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
  515. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  516. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
  517. 2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1 // 0xf0
  518. };
  519. static const char XML_gbk_big5_ByteTable[256] =
  520. {
  521. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  522. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  523. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  524. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  525. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  526. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  527. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  528. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  529. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
  530. 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0xfe 2 bytes
  531. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
  532. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0
  533. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
  534. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
  535. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  536. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
  537. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1 // 0xf0
  538. };
  539. static const char *XML_ByteTable=(const char *)XML_utf8ByteTable; // the default is "characterEncoding=XMLNode::encoding_UTF8"
  540. #endif
  541. XMLNode XMLNode::emptyXMLNode;
  542. XMLClear XMLNode::emptyXMLClear={ NULL, NULL, NULL};
  543. XMLAttribute XMLNode::emptyXMLAttribute={ NULL, NULL};
  544. // Enumeration used to decipher what type a token is
  545. typedef enum XMLTokenTypeTag
  546. {
  547. eTokenText = 0,
  548. eTokenQuotedText,
  549. eTokenTagStart, /* "<" */
  550. eTokenTagEnd, /* "</" */
  551. eTokenCloseTag, /* ">" */
  552. eTokenEquals, /* "=" */
  553. eTokenDeclaration, /* "<?" */
  554. eTokenShortHandClose, /* "/>" */
  555. eTokenClear,
  556. eTokenError
  557. } XMLTokenType;
  558. // Main structure used for parsing XML
  559. typedef struct XML
  560. {
  561. XMLCSTR lpXML;
  562. XMLCSTR lpszText;
  563. int nIndex,nIndexMissigEndTag;
  564. enum XMLError error;
  565. XMLCSTR lpEndTag;
  566. int cbEndTag;
  567. XMLCSTR lpNewElement;
  568. int cbNewElement;
  569. int nFirst;
  570. } XML;
  571. typedef struct
  572. {
  573. ALLXMLClearTag *pClr;
  574. XMLCSTR pStr;
  575. } NextToken;
  576. // Enumeration used when parsing attributes
  577. typedef enum Attrib
  578. {
  579. eAttribName = 0,
  580. eAttribEquals,
  581. eAttribValue
  582. } Attrib;
  583. // Enumeration used when parsing elements to dictate whether we are currently
  584. // inside a tag
  585. typedef enum Status
  586. {
  587. eInsideTag = 0,
  588. eOutsideTag
  589. } Status;
  590. XMLError XMLNode::writeToFile(XMLCSTR filename, const char *encoding, char nFormat) const
  591. {
  592. if (!d) return eXMLErrorNone;
  593. FILE *f=xfopen(filename,_CXML("wb"));
  594. if (!f) return eXMLErrorCannotOpenWriteFile;
  595. #ifdef _XMLWIDECHAR
  596. unsigned char h[2]={ 0xFF, 0xFE };
  597. if (!fwrite(h,2,1,f)) return eXMLErrorCannotWriteFile;
  598. if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
  599. {
  600. if (!fwrite(L"<?xml version=\"1.0\" encoding=\"utf-16\"?>\n",sizeof(wchar_t)*40,1,f))
  601. return eXMLErrorCannotWriteFile;
  602. }
  603. #else
  604. if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
  605. {
  606. if (characterEncoding==char_encoding_UTF8)
  607. {
  608. // header so that windows recognize the file as UTF-8:
  609. unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
  610. encoding="utf-8";
  611. } else if (characterEncoding==char_encoding_ShiftJIS) encoding="SHIFT-JIS";
  612. if (!encoding) encoding="ISO-8859-1";
  613. if (fprintf(f,"<?xml version=\"1.0\" encoding=\"%s\"?>\n",encoding)<0) return eXMLErrorCannotWriteFile;
  614. } else
  615. {
  616. if (characterEncoding==char_encoding_UTF8)
  617. {
  618. unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
  619. }
  620. }
  621. #endif
  622. int i;
  623. XMLSTR t=createXMLString(nFormat,&i);
  624. if (!fwrite(t,sizeof(XMLCHAR)*i,1,f)) return eXMLErrorCannotWriteFile;
  625. if (fclose(f)!=0) return eXMLErrorCannotWriteFile;
  626. free(t);
  627. return eXMLErrorNone;
  628. }
  629. // Duplicate a given string.
  630. XMLSTR stringDup(XMLCSTR lpszData, int cbData)
  631. {
  632. if (lpszData==NULL) return NULL;
  633. XMLSTR lpszNew;
  634. if (cbData==-1) cbData=(int)xstrlen(lpszData);
  635. lpszNew = (XMLSTR)malloc((cbData+1) * sizeof(XMLCHAR));
  636. if (lpszNew)
  637. {
  638. memcpy(lpszNew, lpszData, (cbData) * sizeof(XMLCHAR));
  639. lpszNew[cbData] = (XMLCHAR)NULL;
  640. }
  641. return lpszNew;
  642. }
  643. XMLSTR ToXMLStringTool::toXMLUnSafe(XMLSTR dest,XMLCSTR source)
  644. {
  645. XMLSTR dd=dest;
  646. XMLCHAR ch;
  647. XMLCharacterEntity *entity;
  648. while ((ch=*source))
  649. {
  650. entity=XMLEntities;
  651. do
  652. {
  653. if (ch==entity->c) {xstrcpy(dest,entity->s); dest+=entity->l; source++; goto out_of_loop1; }
  654. entity++;
  655. } while(entity->s);
  656. #ifdef _XMLWIDECHAR
  657. *(dest++)=*(source++);
  658. #else
  659. switch(XML_ByteTable[(unsigned char)ch])
  660. {
  661. case 4: *(dest++)=*(source++);
  662. case 3: *(dest++)=*(source++);
  663. case 2: *(dest++)=*(source++);
  664. case 1: *(dest++)=*(source++);
  665. }
  666. #endif
  667. out_of_loop1:
  668. ;
  669. }
  670. *dest=0;
  671. return dd;
  672. }
  673. // private (used while rendering):
  674. int ToXMLStringTool::lengthXMLString(XMLCSTR source)
  675. {
  676. int r=0;
  677. XMLCharacterEntity *entity;
  678. XMLCHAR ch;
  679. while ((ch=*source))
  680. {
  681. entity=XMLEntities;
  682. do
  683. {
  684. if (ch==entity->c) { r+=entity->l; source++; goto out_of_loop1; }
  685. entity++;
  686. } while(entity->s);
  687. #ifdef _XMLWIDECHAR
  688. r++; source++;
  689. #else
  690. ch=XML_ByteTable[(unsigned char)ch]; r+=ch; source+=ch;
  691. #endif
  692. out_of_loop1:
  693. ;
  694. }
  695. return r;
  696. }
  697. ToXMLStringTool::~ToXMLStringTool(){ freeBuffer(); }
  698. void ToXMLStringTool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; }
  699. XMLSTR ToXMLStringTool::toXML(XMLCSTR source)
  700. {
  701. if (!source) return _CXML("");
  702. int l=lengthXMLString(source)+1;
  703. if (l>buflen) { buflen=l; buf=(XMLSTR)realloc(buf,l*sizeof(XMLCHAR)); }
  704. return toXMLUnSafe(buf,source);
  705. }
  706. // private:
  707. XMLSTR fromXMLString(XMLCSTR s, int lo, XML *pXML)
  708. {
  709. // This function is the opposite of the function "toXMLString". It decodes the escape
  710. // sequences &amp;, &quot;, &apos;, &lt;, &gt; and replace them by the characters
  711. // &,",',<,>. This function is used internally by the XML Parser. All the calls to
  712. // the XML library will always gives you back "decoded" strings.
  713. //
  714. // in: string (s) and length (lo) of string
  715. // out: new allocated string converted from xml
  716. if (!s) return NULL;
  717. int ll=0,j;
  718. XMLSTR d;
  719. XMLCSTR ss=s;
  720. XMLCharacterEntity *entity;
  721. while ((lo>0)&&(*s))
  722. {
  723. if (*s==_CXML('&'))
  724. {
  725. if ((lo>2)&&(s[1]==_CXML('#')))
  726. {
  727. s+=2; lo-=2;
  728. if ((*s==_CXML('X'))||(*s==_CXML('x'))) { s++; lo--; }
  729. while ((*s)&&(*s!=_CXML(';'))&&((lo--)>0)) s++;
  730. if (*s!=_CXML(';'))
  731. {
  732. pXML->error=eXMLErrorUnknownCharacterEntity;
  733. return NULL;
  734. }
  735. s++; lo--;
  736. } else
  737. {
  738. entity=XMLEntities;
  739. do
  740. {
  741. if ((lo>=entity->l)&&(xstrnicmp(s,entity->s,entity->l)==0)) { s+=entity->l; lo-=entity->l; break; }
  742. entity++;
  743. } while(entity->s);
  744. if (!entity->s)
  745. {
  746. pXML->error=eXMLErrorUnknownCharacterEntity;
  747. return NULL;
  748. }
  749. }
  750. } else
  751. {
  752. #ifdef _XMLWIDECHAR
  753. s++; lo--;
  754. #else
  755. j=XML_ByteTable[(unsigned char)*s]; s+=j; lo-=j; ll+=j-1;
  756. #endif
  757. }
  758. ll++;
  759. }
  760. d=(XMLSTR)malloc((ll+1)*sizeof(XMLCHAR));
  761. s=d;
  762. while (ll-->0)
  763. {
  764. if (*ss==_CXML('&'))
  765. {
  766. if (ss[1]==_CXML('#'))
  767. {
  768. ss+=2; j=0;
  769. if ((*ss==_CXML('X'))||(*ss==_CXML('x')))
  770. {
  771. ss++;
  772. while (*ss!=_CXML(';'))
  773. {
  774. if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j<<4)+*ss-_CXML('0');
  775. else if ((*ss>=_CXML('A'))&&(*ss<=_CXML('F'))) j=(j<<4)+*ss-_CXML('A')+10;
  776. else if ((*ss>=_CXML('a'))&&(*ss<=_CXML('f'))) j=(j<<4)+*ss-_CXML('a')+10;
  777. else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
  778. ss++;
  779. }
  780. } else
  781. {
  782. while (*ss!=_CXML(';'))
  783. {
  784. if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j*10)+*ss-_CXML('0');
  785. else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
  786. ss++;
  787. }
  788. }
  789. #ifndef _XMLWIDECHAR
  790. if (j>255) { free((void*)s); pXML->error=eXMLErrorCharacterCodeAbove255;return NULL;}
  791. #endif
  792. (*d++)=(XMLCHAR)j; ss++;
  793. } else
  794. {
  795. entity=XMLEntities;
  796. do
  797. {
  798. if (xstrnicmp(ss,entity->s,entity->l)==0) { *(d++)=entity->c; ss+=entity->l; break; }
  799. entity++;
  800. } while(entity->s);
  801. }
  802. } else
  803. {
  804. #ifdef _XMLWIDECHAR
  805. *(d++)=*(ss++);
  806. #else
  807. switch(XML_ByteTable[(unsigned char)*ss])
  808. {
  809. case 4: *(d++)=*(ss++); ll--;
  810. case 3: *(d++)=*(ss++); ll--;
  811. case 2: *(d++)=*(ss++); ll--;
  812. case 1: *(d++)=*(ss++);
  813. }
  814. #endif
  815. }
  816. }
  817. *d=0;
  818. return (XMLSTR)s;
  819. }
  820. #define XML_isSPACECHAR(ch) ((ch==_CXML('\n'))||(ch==_CXML(' '))||(ch== _CXML('\t'))||(ch==_CXML('\r')))
  821. // private:
  822. char myTagCompare(XMLCSTR cclose, XMLCSTR copen)
  823. // !!!! WARNING strange convention&:
  824. // return 0 if equals
  825. // return 1 if different
  826. {
  827. if (!cclose) return 1;
  828. int l=(int)xstrlen(cclose);
  829. if (xstrnicmp(cclose, copen, l)!=0) return 1;
  830. const XMLCHAR c=copen[l];
  831. if (XML_isSPACECHAR(c)||
  832. (c==_CXML('/' ))||
  833. (c==_CXML('<' ))||
  834. (c==_CXML('>' ))||
  835. (c==_CXML('=' ))) return 0;
  836. return 1;
  837. }
  838. // Obtain the next character from the string.
  839. static inline XMLCHAR getNextChar(XML *pXML)
  840. {
  841. XMLCHAR ch = pXML->lpXML[pXML->nIndex];
  842. #ifdef _XMLWIDECHAR
  843. if (ch!=0) pXML->nIndex++;
  844. #else
  845. pXML->nIndex+=XML_ByteTable[(unsigned char)ch];
  846. #endif
  847. return ch;
  848. }
  849. // Find the next token in a string.
  850. // pcbToken contains the number of characters that have been read.
  851. static NextToken GetNextToken(XML *pXML, int *pcbToken, enum XMLTokenTypeTag *pType)
  852. {
  853. NextToken result;
  854. XMLCHAR ch;
  855. XMLCHAR chTemp;
  856. int indexStart,nFoundMatch,nIsText=FALSE;
  857. result.pClr=NULL; // prevent warning
  858. // Find next non-white space character
  859. do { indexStart=pXML->nIndex; ch=getNextChar(pXML); } while XML_isSPACECHAR(ch);
  860. if (ch)
  861. {
  862. // Cache the current string pointer
  863. result.pStr = &pXML->lpXML[indexStart];
  864. // First check whether the token is in the clear tag list (meaning it
  865. // does not need formatting).
  866. ALLXMLClearTag *ctag=XMLClearTags;
  867. do
  868. {
  869. if (xstrncmp(ctag->lpszOpen, result.pStr, ctag->openTagLen)==0)
  870. {
  871. result.pClr=ctag;
  872. pXML->nIndex+=ctag->openTagLen-1;
  873. *pType=eTokenClear;
  874. return result;
  875. }
  876. ctag++;
  877. } while(ctag->lpszOpen);
  878. // If we didn't find a clear tag then check for standard tokens
  879. switch(ch)
  880. {
  881. // Check for quotes
  882. case _CXML('\''):
  883. case _CXML('\"'):
  884. // Type of token
  885. *pType = eTokenQuotedText;
  886. chTemp = ch;
  887. // Set the size
  888. nFoundMatch = FALSE;
  889. // Search through the string to find a matching quote
  890. while((ch = getNextChar(pXML)))
  891. {
  892. if (ch==chTemp) { nFoundMatch = TRUE; break; }
  893. if (ch==_CXML('<')) break;
  894. }
  895. // If we failed to find a matching quote
  896. if (nFoundMatch == FALSE)
  897. {
  898. pXML->nIndex=indexStart+1;
  899. nIsText=TRUE;
  900. break;
  901. }
  902. // 4.02.2002
  903. // if (FindNonWhiteSpace(pXML)) pXML->nIndex--;
  904. break;
  905. // Equals (used with attribute values)
  906. case _CXML('='):
  907. *pType = eTokenEquals;
  908. break;
  909. // Close tag
  910. case _CXML('>'):
  911. *pType = eTokenCloseTag;
  912. break;
  913. // Check for tag start and tag end
  914. case _CXML('<'):
  915. // Peek at the next character to see if we have an end tag '</',
  916. // or an xml declaration '<?'
  917. chTemp = pXML->lpXML[pXML->nIndex];
  918. // If we have a tag end...
  919. if (chTemp == _CXML('/'))
  920. {
  921. // Set the type and ensure we point at the next character
  922. getNextChar(pXML);
  923. *pType = eTokenTagEnd;
  924. }
  925. // If we have an XML declaration tag
  926. else if (chTemp == _CXML('?'))
  927. {
  928. // Set the type and ensure we point at the next character
  929. getNextChar(pXML);
  930. *pType = eTokenDeclaration;
  931. }
  932. // Otherwise we must have a start tag
  933. else
  934. {
  935. *pType = eTokenTagStart;
  936. }
  937. break;
  938. // Check to see if we have a short hand type end tag ('/>').
  939. case _CXML('/'):
  940. // Peek at the next character to see if we have a short end tag '/>'
  941. chTemp = pXML->lpXML[pXML->nIndex];
  942. // If we have a short hand end tag...
  943. if (chTemp == _CXML('>'))
  944. {
  945. // Set the type and ensure we point at the next character
  946. getNextChar(pXML);
  947. *pType = eTokenShortHandClose;
  948. break;
  949. }
  950. // If we haven't found a short hand closing tag then drop into the
  951. // text process
  952. // Other characters
  953. default:
  954. nIsText = TRUE;
  955. }
  956. // If this is a TEXT node
  957. if (nIsText)
  958. {
  959. // Indicate we are dealing with text
  960. *pType = eTokenText;
  961. while((ch = getNextChar(pXML)))
  962. {
  963. if XML_isSPACECHAR(ch)
  964. {
  965. indexStart++; break;
  966. } else if (ch==_CXML('/'))
  967. {
  968. // If we find a slash then this maybe text or a short hand end tag
  969. // Peek at the next character to see it we have short hand end tag
  970. ch=pXML->lpXML[pXML->nIndex];
  971. // If we found a short hand end tag then we need to exit the loop
  972. if (ch==_CXML('>')) { pXML->nIndex--; break; }
  973. } else if ((ch==_CXML('<'))||(ch==_CXML('>'))||(ch==_CXML('=')))
  974. {
  975. pXML->nIndex--; break;
  976. }
  977. }
  978. }
  979. *pcbToken = pXML->nIndex-indexStart;
  980. } else
  981. {
  982. // If we failed to obtain a valid character
  983. *pcbToken = 0;
  984. *pType = eTokenError;
  985. result.pStr=NULL;
  986. }
  987. return result;
  988. }
  989. XMLCSTR XMLNode::updateName_WOSD(XMLSTR lpszName)
  990. {
  991. if (!d) { free(lpszName); return NULL; }
  992. if (d->lpszName&&(lpszName!=d->lpszName)) free((void*)d->lpszName);
  993. d->lpszName=lpszName;
  994. return lpszName;
  995. }
  996. // private:
  997. XMLNode::XMLNode(struct XMLNodeDataTag *p){ d=p; (p->ref_count)++; }
  998. XMLNode::XMLNode(XMLNodeData *pParent, XMLSTR lpszName, char isDeclaration)
  999. {
  1000. d=(XMLNodeData*)malloc(sizeof(XMLNodeData));
  1001. d->ref_count=1;
  1002. d->lpszName=NULL;
  1003. d->nChild= 0;
  1004. d->nText = 0;
  1005. d->nClear = 0;
  1006. d->nAttribute = 0;
  1007. d->isDeclaration = isDeclaration;
  1008. d->pParent = pParent;
  1009. d->pChild= NULL;
  1010. d->pText= NULL;
  1011. d->pClear= NULL;
  1012. d->pAttribute= NULL;
  1013. d->pOrder= NULL;
  1014. updateName_WOSD(lpszName);
  1015. }
  1016. XMLNode XMLNode::createXMLTopNode_WOSD(XMLSTR lpszName, char isDeclaration) { return XMLNode(NULL,lpszName,isDeclaration); }
  1017. XMLNode XMLNode::createXMLTopNode(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,stringDup(lpszName),isDeclaration); }
  1018. #define MEMORYINCREASE 50
  1019. static inline void myFree(void *p) { if (p) free(p); }
  1020. static inline void *myRealloc(void *p, int newsize, int memInc, int sizeofElem)
  1021. {
  1022. if (p==NULL) { if (memInc) return malloc(memInc*sizeofElem); return malloc(sizeofElem); }
  1023. if ((memInc==0)||((newsize%memInc)==0)) p=realloc(p,(newsize+memInc)*sizeofElem);
  1024. // if (!p)
  1025. // {
  1026. // printf("XMLParser Error: Not enough memory! Aborting...\n"); exit(220);
  1027. // }
  1028. return p;
  1029. }
  1030. // private:
  1031. XMLElementPosition XMLNode::findPosition(XMLNodeData *d, int index, XMLElementType xxtype)
  1032. {
  1033. if (index<0) return -1;
  1034. int i=0,j=(int)((index<<2)+xxtype),*o=d->pOrder; while (o[i]!=j) i++; return i;
  1035. }
  1036. // private:
  1037. // update "order" information when deleting a content of a XMLNode
  1038. int XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index)
  1039. {
  1040. int n=d->nChild+d->nText+d->nClear, *o=d->pOrder,i=findPosition(d,index,t);
  1041. memmove(o+i, o+i+1, (n-i)*sizeof(int));
  1042. for (;i<n;i++)
  1043. if ((o[i]&3)==(int)t) o[i]-=4;
  1044. // We should normally do:
  1045. // d->pOrder=(int)realloc(d->pOrder,n*sizeof(int));
  1046. // but we skip reallocation because it's too time consuming.
  1047. // Anyway, at the end, it will be free'd completely at once.
  1048. return i;
  1049. }
  1050. void *XMLNode::addToOrder(int memoryIncrease,int *_pos, int nc, void *p, int size, XMLElementType xtype)
  1051. {
  1052. // in: *_pos is the position inside d->pOrder ("-1" means "EndOf")
  1053. // out: *_pos is the index inside p
  1054. p=myRealloc(p,(nc+1),memoryIncrease,size);
  1055. int n=d->nChild+d->nText+d->nClear;
  1056. d->pOrder=(int*)myRealloc(d->pOrder,n+1,memoryIncrease*3,sizeof(int));
  1057. int pos=*_pos,*o=d->pOrder;
  1058. if ((pos<0)||(pos>=n)) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
  1059. int i=pos;
  1060. memmove(o+i+1, o+i, (n-i)*sizeof(int));
  1061. while ((pos<n)&&((o[pos]&3)!=(int)xtype)) pos++;
  1062. if (pos==n) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
  1063. o[i]=o[pos];
  1064. for (i=pos+1;i<=n;i++) if ((o[i]&3)==(int)xtype) o[i]+=4;
  1065. *_pos=pos=o[pos]>>2;
  1066. memmove(((char*)p)+(pos+1)*size,((char*)p)+pos*size,(nc-pos)*size);
  1067. return p;
  1068. }
  1069. // Add a child node to the given element.
  1070. XMLNode XMLNode::addChild_priv(int memoryIncrease, XMLSTR lpszName, char isDeclaration, int pos)
  1071. {
  1072. if (!lpszName) return emptyXMLNode;
  1073. d->pChild=(XMLNode*)addToOrder(memoryIncrease,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
  1074. d->pChild[pos].d=NULL;
  1075. d->pChild[pos]=XMLNode(d,lpszName,isDeclaration);
  1076. d->nChild++;
  1077. return d->pChild[pos];
  1078. }
  1079. // Add an attribute to an element.
  1080. XMLAttribute *XMLNode::addAttribute_priv(int memoryIncrease,XMLSTR lpszName, XMLSTR lpszValuev)
  1081. {
  1082. if (!lpszName) return &emptyXMLAttribute;
  1083. if (!d) { myFree(lpszName); myFree(lpszValuev); return &emptyXMLAttribute; }
  1084. int nc=d->nAttribute;
  1085. d->pAttribute=(XMLAttribute*)myRealloc(d->pAttribute,(nc+1),memoryIncrease,sizeof(XMLAttribute));
  1086. XMLAttribute *pAttr=d->pAttribute+nc;
  1087. pAttr->lpszName = lpszName;
  1088. pAttr->lpszValue = lpszValuev;
  1089. d->nAttribute++;
  1090. return pAttr;
  1091. }
  1092. // Add text to the element.
  1093. XMLCSTR XMLNode::addText_priv(int memoryIncrease, XMLSTR lpszValue, int pos)
  1094. {
  1095. if (!lpszValue) return NULL;
  1096. if (!d) { myFree(lpszValue); return NULL; }
  1097. d->pText=(XMLCSTR*)addToOrder(memoryIncrease,&pos,d->nText,d->pText,sizeof(XMLSTR),eNodeText);
  1098. d->pText[pos]=lpszValue;
  1099. d->nText++;
  1100. return lpszValue;
  1101. }
  1102. // Add clear (unformatted) text to the element.
  1103. XMLClear *XMLNode::addClear_priv(int memoryIncrease, XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
  1104. {
  1105. if (!lpszValue) return &emptyXMLClear;
  1106. if (!d) { myFree(lpszValue); return &emptyXMLClear; }
  1107. d->pClear=(XMLClear *)addToOrder(memoryIncrease,&pos,d->nClear,d->pClear,sizeof(XMLClear),eNodeClear);
  1108. XMLClear *pNewClear=d->pClear+pos;
  1109. pNewClear->lpszValue = lpszValue;
  1110. if (!lpszOpen) lpszOpen=XMLClearTags->lpszOpen;
  1111. if (!lpszClose) lpszClose=XMLClearTags->lpszClose;
  1112. pNewClear->lpszOpenTag = lpszOpen;
  1113. pNewClear->lpszCloseTag = lpszClose;
  1114. d->nClear++;
  1115. return pNewClear;
  1116. }
  1117. // private:
  1118. // Parse a clear (unformatted) type node.
  1119. char XMLNode::parseClearTag(void *px, void *_pClear)
  1120. {
  1121. XML *pXML=(XML *)px;
  1122. ALLXMLClearTag pClear=*((ALLXMLClearTag*)_pClear);
  1123. int cbTemp=0;
  1124. XMLCSTR lpszTemp=NULL;
  1125. XMLCSTR lpXML=&pXML->lpXML[pXML->nIndex];
  1126. static XMLCSTR docTypeEnd=_CXML("]>");
  1127. // Find the closing tag
  1128. // Seems the <!DOCTYPE need a better treatment so lets handle it
  1129. if (pClear.lpszOpen==XMLClearTags[1].lpszOpen)
  1130. {
  1131. XMLCSTR pCh=lpXML;
  1132. while (*pCh)
  1133. {
  1134. if (*pCh==_CXML('<')) { pClear.lpszClose=docTypeEnd; lpszTemp=xstrstr(lpXML,docTypeEnd); break; }
  1135. else if (*pCh==_CXML('>')) { lpszTemp=pCh; break; }
  1136. #ifdef _XMLWIDECHAR
  1137. pCh++;
  1138. #else
  1139. pCh+=XML_ByteTable[(unsigned char)(*pCh)];
  1140. #endif
  1141. }
  1142. } else lpszTemp=xstrstr(lpXML, pClear.lpszClose);
  1143. if (lpszTemp)
  1144. {
  1145. // Cache the size and increment the index
  1146. cbTemp = (int)(lpszTemp - lpXML);
  1147. pXML->nIndex += cbTemp+(int)xstrlen(pClear.lpszClose);
  1148. // Add the clear node to the current element
  1149. addClear_priv(MEMORYINCREASE,stringDup(lpXML,cbTemp), pClear.lpszOpen, pClear.lpszClose,-1);
  1150. return 0;
  1151. }
  1152. // If we failed to find the end tag
  1153. pXML->error = eXMLErrorUnmatchedEndClearTag;
  1154. return 1;
  1155. }
  1156. void XMLNode::exactMemory(XMLNodeData *d)
  1157. {
  1158. if (d->pOrder) d->pOrder=(int*)realloc(d->pOrder,(d->nChild+d->nText+d->nClear)*sizeof(int));
  1159. if (d->pChild) d->pChild=(XMLNode*)realloc(d->pChild,d->nChild*sizeof(XMLNode));
  1160. if (d->pAttribute) d->pAttribute=(XMLAttribute*)realloc(d->pAttribute,d->nAttribute*sizeof(XMLAttribute));
  1161. if (d->pText) d->pText=(XMLCSTR*)realloc(d->pText,d->nText*sizeof(XMLSTR));
  1162. if (d->pClear) d->pClear=(XMLClear *)realloc(d->pClear,d->nClear*sizeof(XMLClear));
  1163. }
  1164. char XMLNode::maybeAddTxT(void *pa, XMLCSTR tokenPStr)
  1165. {
  1166. XML *pXML=(XML *)pa;
  1167. XMLCSTR lpszText=pXML->lpszText;
  1168. if (!lpszText) return 0;
  1169. if (dropWhiteSpace) while (XML_isSPACECHAR(*lpszText)&&(lpszText!=tokenPStr)) lpszText++;
  1170. int cbText = (int)(tokenPStr - lpszText);
  1171. if (!cbText) { pXML->lpszText=NULL; return 0; }
  1172. if (dropWhiteSpace) { cbText--; while ((cbText)&&XML_isSPACECHAR(lpszText[cbText])) cbText--; cbText++; }
  1173. if (!cbText) { pXML->lpszText=NULL; return 0; }
  1174. XMLSTR lpt=fromXMLString(lpszText,cbText,pXML);
  1175. if (!lpt) return 1;
  1176. pXML->lpszText=NULL;
  1177. if (removeCommentsInMiddleOfText && d->nText && d->nClear)
  1178. {
  1179. // if the previous insertion was a comment (<!-- -->) AND
  1180. // if the previous previous insertion was a text then, delete the comment and append the text
  1181. int n=d->nChild+d->nText+d->nClear-1,*o=d->pOrder;
  1182. if (((o[n]&3)==eNodeClear)&&((o[n-1]&3)==eNodeText))

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