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

/xmlParser.cpp

https://bitbucket.org/alan_cao/code123
C++ | 2888 lines | 2290 code | 228 blank | 370 comment | 470 complexity | 305cef3dec8429501ffd3f1e4dda9df3 MD5 | raw file

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

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