PageRenderTime 62ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/base/src/utils/xmlparser/xmlParser.cpp

http://github.com/gamman/MRPT
C++ | 2836 lines | 2262 code | 228 blank | 346 comment | 468 complexity | e8a57226a5cecf99716b251990b28efb MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause
  1. /* +---------------------------------------------------------------------------+
  2. | The Mobile Robot Programming Toolkit (MRPT) C++ library |
  3. | |
  4. | http://www.mrpt.org/ |
  5. | |
  6. | Copyright (C) 2005-2011 University of Malaga |
  7. | |
  8. | This software was written by the Machine Perception and Intelligent |
  9. | Robotics Lab, University of Malaga (Spain). |
  10. | Contact: Jose-Luis Blanco <jlblanco@ctima.uma.es> |
  11. | |
  12. | This file is part of the MRPT project. |
  13. | |
  14. | MRPT is free software: you can redistribute it and/or modify |
  15. | it under the terms of the GNU General Public License as published by |
  16. | the Free Software Foundation, either version 3 of the License, or |
  17. | (at your option) any later version. |
  18. | |
  19. | MRPT is distributed in the hope that it will be useful, |
  20. | but WITHOUT ANY WARRANTY; without even the implied warranty of |
  21. | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
  22. | GNU General Public License for more details. |
  23. | |
  24. | You should have received a copy of the GNU General Public License |
  25. | along with MRPT. If not, see <http://www.gnu.org/licenses/>. |
  26. | |
  27. +---------------------------------------------------------------------------+ */
  28. #ifndef _CRT_SECURE_NO_DEPRECATE
  29. #define _CRT_SECURE_NO_DEPRECATE
  30. #endif
  31. #undef _UNICODE // JLBC
  32. #include "xmlParser.h"
  33. #ifdef _XMLWINDOWS
  34. //#ifdef _DEBUG
  35. //#define _CRTDBG_MAP_ALLOC
  36. //#include <crtdbg.h>
  37. //#endif
  38. #define WIN32_LEAN_AND_MEAN
  39. #include <Windows.h> // to have IsTextUnicode, MultiByteToWideChar, WideCharToMultiByte to handle unicode files
  40. // to have "MessageBoxA" to display error messages for openFilHelper
  41. #endif
  42. #include <memory.h>
  43. #include <assert.h>
  44. #include <stdio.h>
  45. #include <string.h>
  46. #include <stdlib.h>
  47. XMLCSTR XMLNode::getVersion() { return _CXML("v2.39"); }
  48. void freeXMLString(XMLSTR t){if(t)free(t);}
  49. static XMLNode::XMLCharEncoding characterEncoding=XMLNode::char_encoding_UTF8;
  50. static char guessWideCharChars=1, dropWhiteSpace=1, removeCommentsInMiddleOfText=1;
  51. inline int mmin( const int t1, const int t2 ) { return t1 < t2 ? t1 : t2; }
  52. // You can modify the initialization of the variable "XMLClearTags" below
  53. // to change the clearTags that are currently recognized by the library.
  54. // The number on the second columns is the length of the string inside the
  55. // first column. The "<!DOCTYPE" declaration must be the second in the list.
  56. // The "<!--" declaration must be the third in the list.
  57. typedef struct { XMLCSTR lpszOpen; int openTagLen; XMLCSTR lpszClose;} ALLXMLClearTag;
  58. static ALLXMLClearTag XMLClearTags[] =
  59. {
  60. { _CXML("<![CDATA["),9, _CXML("]]>") },
  61. { _CXML("<!DOCTYPE"),9, _CXML(">") },
  62. { _CXML("<!--") ,4, _CXML("-->") },
  63. { _CXML("<PRE>") ,5, _CXML("</PRE>") },
  64. // { _CXML("<Script>") ,8, _CXML("</Script>")},
  65. { NULL ,0, NULL }
  66. };
  67. // You can modify the initialization of the variable "XMLEntities" below
  68. // to change the character entities that are currently recognized by the library.
  69. // The number on the second columns is the length of the string inside the
  70. // first column. Additionally, the syntaxes "&#xA0;" and "&#160;" are recognized.
  71. typedef struct { XMLCSTR s; int l; XMLCHAR c;} XMLCharacterEntity;
  72. static XMLCharacterEntity XMLEntities[] =
  73. {
  74. { _CXML("&amp;" ), 5, _CXML('&' )},
  75. { _CXML("&lt;" ), 4, _CXML('<' )},
  76. { _CXML("&gt;" ), 4, _CXML('>' )},
  77. { _CXML("&quot;"), 6, _CXML('\"')},
  78. { _CXML("&apos;"), 6, _CXML('\'')},
  79. { NULL , 0, '\0' }
  80. };
  81. // When rendering the XMLNode to a string (using the "createXMLString" function),
  82. // you can ask for a beautiful formatting. This formatting is using the
  83. // following indentation character:
  84. #define INDENTCHAR _CXML('\t')
  85. // The following function parses the XML errors into a user friendly string.
  86. // You can edit this to change the output language of the library to something else.
  87. XMLCSTR XMLNode::getError(XMLError xerror)
  88. {
  89. switch (xerror)
  90. {
  91. case eXMLErrorNone: return _CXML("No error");
  92. case eXMLErrorMissingEndTag: return _CXML("Warning: Unmatched end tag");
  93. case eXMLErrorNoXMLTagFound: return _CXML("Warning: No XML tag found");
  94. case eXMLErrorEmpty: return _CXML("Error: No XML data");
  95. case eXMLErrorMissingTagName: return _CXML("Error: Missing start tag name");
  96. case eXMLErrorMissingEndTagName: return _CXML("Error: Missing end tag name");
  97. case eXMLErrorUnmatchedEndTag: return _CXML("Error: Unmatched end tag");
  98. case eXMLErrorUnmatchedEndClearTag: return _CXML("Error: Unmatched clear tag end");
  99. case eXMLErrorUnexpectedToken: return _CXML("Error: Unexpected token found");
  100. case eXMLErrorNoElements: return _CXML("Error: No elements found");
  101. case eXMLErrorFileNotFound: return _CXML("Error: File not found");
  102. case eXMLErrorFirstTagNotFound: return _CXML("Error: First Tag not found");
  103. case eXMLErrorUnknownCharacterEntity:return _CXML("Error: Unknown character entity");
  104. case eXMLErrorCharacterCodeAbove255: return _CXML("Error: Character code above 255 is forbidden in MultiByte char mode.");
  105. case eXMLErrorCharConversionError: return _CXML("Error: unable to convert between WideChar and MultiByte chars");
  106. case eXMLErrorCannotOpenWriteFile: return _CXML("Error: unable to open file for writing");
  107. case eXMLErrorCannotWriteFile: return _CXML("Error: cannot write into file");
  108. case eXMLErrorBase64DataSizeIsNotMultipleOf4: return _CXML("Warning: Base64-string length is not a multiple of 4");
  109. case eXMLErrorBase64DecodeTruncatedData: return _CXML("Warning: Base64-string is truncated");
  110. case eXMLErrorBase64DecodeIllegalCharacter: return _CXML("Error: Base64-string contains an illegal character");
  111. case eXMLErrorBase64DecodeBufferTooSmall: return _CXML("Error: Base64 decode output buffer is too small");
  112. };
  113. return _CXML("Unknown");
  114. }
  115. /////////////////////////////////////////////////////////////////////////
  116. // Here start the abstraction layer to be OS-independent //
  117. /////////////////////////////////////////////////////////////////////////
  118. // Here is an abstraction layer to access some common string manipulation functions.
  119. // The abstraction layer is currently working for gcc, Microsoft Visual Studio 6.0,
  120. // Microsoft Visual Studio .NET, CC (sun compiler) and Borland C++.
  121. // If you plan to "port" the library to a new system/compiler, all you have to do is
  122. // to edit the following lines.
  123. #ifdef XML_NO_WIDE_CHAR
  124. char myIsTextWideChar(const void *b, int len) { return FALSE; }
  125. #else
  126. #if defined (UNDER_CE) || !defined(_XMLWINDOWS)
  127. char myIsTextWideChar(const void *b, int len) // inspired by the Wine API: RtlIsTextUnicode
  128. {
  129. #ifdef sun
  130. // for SPARC processors: wchar_t* buffers must always be alligned, otherwise it's a char* buffer.
  131. if ((((unsigned long)b)%sizeof(wchar_t))!=0) return FALSE;
  132. #endif
  133. const wchar_t *s=(const wchar_t*)b;
  134. // buffer too small:
  135. if (len<(int)sizeof(wchar_t)) return FALSE;
  136. // odd length test
  137. if (len&1) return FALSE;
  138. /* only checks the first 256 characters */
  139. len=mmin(256,len/sizeof(wchar_t));
  140. // Check for the special byte order:
  141. if (*((unsigned short*)s) == 0xFFFE) return TRUE; // IS_TEXT_UNICODE_REVERSE_SIGNATURE;
  142. if (*((unsigned short*)s) == 0xFEFF) return TRUE; // IS_TEXT_UNICODE_SIGNATURE
  143. // checks for ASCII characters in the UNICODE stream
  144. int i,stats=0;
  145. for (i=0; i<len; i++) if (s[i]<=(unsigned short)255) stats++;
  146. if (stats>len/2) return TRUE;
  147. // Check for UNICODE NULL chars
  148. for (i=0; i<len; i++) if (!s[i]) return TRUE;
  149. return FALSE;
  150. }
  151. #else
  152. char myIsTextWideChar(const void *b,int l) { return (char)IsTextUnicode((CONST LPVOID)b,l,NULL); }
  153. #endif
  154. #endif
  155. #ifdef _XMLWINDOWS
  156. // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0
  157. #ifdef _XMLWIDECHAR
  158. wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce)
  159. {
  160. int i;
  161. if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,-1,NULL,0);
  162. else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,NULL,0);
  163. if (i<0) return NULL;
  164. wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(XMLCHAR));
  165. if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,-1,d,i);
  166. else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,d,i);
  167. d[i]=0;
  168. return d;
  169. }
  170. static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return _wfopen(filename,mode); }
  171. static inline int xstrlen(XMLCSTR c) { return (int)wcslen(c); }
  172. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _wcsnicmp(c1,c2,l);}
  173. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);}
  174. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _wcsicmp(c1,c2); }
  175. static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
  176. static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
  177. #else
  178. char *myWideCharToMultiByte(const wchar_t *s)
  179. {
  180. UINT codePage=CP_ACP; if (characterEncoding==XMLNode::char_encoding_UTF8) codePage=CP_UTF8;
  181. int i=(int)WideCharToMultiByte(codePage, // code page
  182. 0, // performance and mapping flags
  183. s, // wide-character string
  184. -1, // number of chars in string
  185. NULL, // buffer for new string
  186. 0, // size of buffer
  187. NULL, // default for unmappable chars
  188. NULL // set when default char used
  189. );
  190. if (i<0) return NULL;
  191. char *d=(char*)malloc(i+1);
  192. WideCharToMultiByte(codePage, // code page
  193. 0, // performance and mapping flags
  194. s, // wide-character string
  195. -1, // number of chars in string
  196. d, // buffer for new string
  197. i, // size of buffer
  198. NULL, // default for unmappable chars
  199. NULL // set when default char used
  200. );
  201. d[i]=0;
  202. return d;
  203. }
  204. static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
  205. static inline int xstrlen(XMLCSTR c) { return (int)strlen(c); }
  206. #ifdef __BORLANDC__
  207. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strnicmp(c1,c2,l);}
  208. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return stricmp(c1,c2); }
  209. #else
  210. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _strnicmp(c1,c2,l);}
  211. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _stricmp(c1,c2); }
  212. #endif
  213. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);}
  214. static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
  215. static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
  216. #endif
  217. #else
  218. // for gcc and CC
  219. #ifdef XML_NO_WIDE_CHAR
  220. char *myWideCharToMultiByte(const wchar_t *s) { return NULL; }
  221. #else
  222. char *myWideCharToMultiByte(const wchar_t *s)
  223. {
  224. const wchar_t *ss=s;
  225. int i=(int)wcsrtombs(NULL,&ss,0,NULL);
  226. if (i<0) return NULL;
  227. char *d=(char *)malloc(i+1);
  228. wcsrtombs(d,&s,i,NULL);
  229. d[i]=0;
  230. return d;
  231. }
  232. #endif
  233. #ifdef _XMLWIDECHAR
  234. wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce)
  235. {
  236. const char *ss=s;
  237. int i=(int)mbsrtowcs(NULL,&ss,0,NULL);
  238. if (i<0) return NULL;
  239. wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(wchar_t));
  240. mbsrtowcs(d,&s,i,NULL);
  241. d[i]=0;
  242. return d;
  243. }
  244. int xstrlen(XMLCSTR c) { return wcslen(c); }
  245. #ifdef sun
  246. // for CC
  247. #include <widec.h>
  248. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncasecmp(c1,c2,l);}
  249. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncmp(c1,c2,l);}
  250. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wscasecmp(c1,c2); }
  251. #else
  252. // for gcc
  253. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncasecmp(c1,c2,l);}
  254. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);}
  255. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wcscasecmp(c1,c2); }
  256. #endif
  257. static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
  258. static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
  259. static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode)
  260. {
  261. char *filenameAscii=myWideCharToMultiByte(filename);
  262. FILE *f;
  263. if (mode[0]==_CXML('r')) f=fopen(filenameAscii,"rb");
  264. else f=fopen(filenameAscii,"wb");
  265. free(filenameAscii);
  266. return f;
  267. }
  268. #else
  269. static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
  270. static inline int xstrlen(XMLCSTR c) { return strlen(c); }
  271. static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncasecmp(c1,c2,l);}
  272. static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);}
  273. static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return strcasecmp(c1,c2); }
  274. static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
  275. static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
  276. #endif
  277. static inline int _strnicmp(const char *c1,const char *c2, int l) { return strncasecmp(c1,c2,l);}
  278. #endif
  279. ///////////////////////////////////////////////////////////////////////////////
  280. // the "xmltoc,xmltob,xmltoi,xmltol,xmltof,xmltoa" functions //
  281. ///////////////////////////////////////////////////////////////////////////////
  282. // These 6 functions are not used inside the XMLparser.
  283. // There are only here as "convenience" functions for the user.
  284. // If you don't need them, you can delete them without any trouble.
  285. #ifdef _XMLWIDECHAR
  286. #ifdef _XMLWINDOWS
  287. // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0
  288. char xmltob(XMLCSTR t,int v){ if (t&&(*t)) return (char)_wtoi(t); return v; }
  289. int xmltoi(XMLCSTR t,int v){ if (t&&(*t)) return _wtoi(t); return v; }
  290. long xmltol(XMLCSTR t,long v){ if (t&&(*t)) return _wtol(t); return v; }
  291. double xmltof(XMLCSTR t,double v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; }
  292. #else
  293. #ifdef sun
  294. // for CC
  295. #include <widec.h>
  296. char xmltob(XMLCSTR t,int v){ if (t) return (char)wstol(t,NULL,10); return v; }
  297. int xmltoi(XMLCSTR t,int v){ if (t) return (int)wstol(t,NULL,10); return v; }
  298. long xmltol(XMLCSTR t,long v){ if (t) return wstol(t,NULL,10); return v; }
  299. #else
  300. // for gcc
  301. char xmltob(XMLCSTR t,int v){ if (t) return (char)wcstol(t,NULL,10); return v; }
  302. int xmltoi(XMLCSTR t,int v){ if (t) return (int)wcstol(t,NULL,10); return v; }
  303. long xmltol(XMLCSTR t,long v){ if (t) return wcstol(t,NULL,10); return v; }
  304. #endif
  305. double xmltof(XMLCSTR t,double v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; }
  306. #endif
  307. #else
  308. char xmltob(XMLCSTR t,char v){ if (t&&(*t)) return (char)atoi(t); return v; }
  309. int xmltoi(XMLCSTR t,int v){ if (t&&(*t)) return atoi(t); return v; }
  310. long xmltol(XMLCSTR t,long v){ if (t&&(*t)) return atol(t); return v; }
  311. double xmltof(XMLCSTR t,double v){ if (t&&(*t)) return atof(t); return v; }
  312. #endif
  313. XMLCSTR xmltoa(XMLCSTR t,XMLCSTR v){ if (t) return t; return v; }
  314. XMLCHAR xmltoc(XMLCSTR t,XMLCHAR v){ if (t&&(*t)) return *t; return v; }
  315. /////////////////////////////////////////////////////////////////////////
  316. // the "openFileHelper" function //
  317. /////////////////////////////////////////////////////////////////////////
  318. // Since each application has its own way to report and deal with errors, you should modify & rewrite
  319. // the following "openFileHelper" function to get an "error reporting mechanism" tailored to your needs.
  320. XMLNode XMLNode::openFileHelper(XMLCSTR filename, XMLCSTR tag)
  321. {
  322. // guess the value of the global parameter "characterEncoding"
  323. // (the guess is based on the first 200 bytes of the file).
  324. FILE *f=xfopen(filename,_CXML("rb"));
  325. if (f)
  326. {
  327. char bb[205];
  328. int l=(int)fread(bb,1,200,f);
  329. setGlobalOptions(guessCharEncoding(bb,l),guessWideCharChars,dropWhiteSpace,removeCommentsInMiddleOfText);
  330. fclose(f);
  331. }
  332. // parse the file
  333. XMLResults pResults;
  334. XMLNode xnode=XMLNode::parseFile(filename,tag,&pResults);
  335. // display error message (if any)
  336. if (pResults.error != eXMLErrorNone)
  337. {
  338. // create message
  339. char message[2000],*s1=(char*)"",*s3=(char*)""; XMLCSTR s2=_CXML("");
  340. if (pResults.error==eXMLErrorFirstTagNotFound) { s1=(char*)"First Tag should be '"; s2=tag; s3=(char*)"'.\n"; }
  341. sprintf(message,
  342. #ifdef _XMLWIDECHAR
  343. "XML Parsing error inside file '%S'.\n%S\nAt line %i, column %i.\n%s%S%s"
  344. #else
  345. "XML Parsing error inside file '%s'.\n%s\nAt line %i, column %i.\n%s%s%s"
  346. #endif
  347. ,filename,XMLNode::getError(pResults.error),pResults.nLine,pResults.nColumn,s1,s2,s3);
  348. // display message
  349. #if defined(_XMLWINDOWS) && !defined(UNDER_CE) && !defined(_XMLPARSER_NO_MESSAGEBOX_)
  350. MessageBoxA(NULL,message,"XML Parsing error",MB_OK|MB_ICONERROR|MB_TOPMOST);
  351. #else
  352. printf("%s",message);
  353. #endif
  354. // exit(255);
  355. }
  356. return xnode;
  357. }
  358. /////////////////////////////////////////////////////////////////////////
  359. // Here start the core implementation of the XMLParser library //
  360. /////////////////////////////////////////////////////////////////////////
  361. // You should normally not change anything below this point.
  362. #ifndef _XMLWIDECHAR
  363. // If "characterEncoding=ascii" then we assume that all characters have the same length of 1 byte.
  364. // If "characterEncoding=UTF8" then the characters have different lengths (from 1 byte to 4 bytes).
  365. // If "characterEncoding=ShiftJIS" then the characters have different lengths (from 1 byte to 2 bytes).
  366. // This table is used as lookup-table to know the length of a character (in byte) based on the
  367. // content of the first byte of the character.
  368. // (note: if you modify this, you must always have XML_utf8ByteTable[0]=0 ).
  369. static const char XML_utf8ByteTable[256] =
  370. {
  371. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  372. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  373. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  374. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  375. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  376. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  377. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  378. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  379. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70 End of ASCII range
  380. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 0x80 to 0xc1 invalid
  381. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
  382. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
  383. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
  384. 1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 0xc2 to 0xdf 2 byte
  385. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  386. 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,// 0xe0 0xe0 to 0xef 3 byte
  387. 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
  388. };
  389. static const char XML_legacyByteTable[256] =
  390. {
  391. 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,
  392. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  393. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  394. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  395. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  396. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  397. };
  398. static const char XML_sjisByteTable[256] =
  399. {
  400. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  401. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  402. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  403. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  404. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  405. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  406. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  407. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  408. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
  409. 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0x9F 2 bytes
  410. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
  411. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
  412. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
  413. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xc0
  414. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xd0
  415. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0 0xe0 to 0xef 2 bytes
  416. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 // 0xf0
  417. };
  418. static const char XML_gb2312ByteTable[256] =
  419. {
  420. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  421. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  422. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  423. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  424. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  425. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  426. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  427. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  428. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
  429. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80
  430. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
  431. 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0 0xa1 to 0xf7 2 bytes
  432. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
  433. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
  434. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  435. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
  436. 2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1 // 0xf0
  437. };
  438. static const char XML_gbk_big5_ByteTable[256] =
  439. {
  440. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  441. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  442. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  443. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  444. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  445. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  446. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  447. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  448. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
  449. 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0xfe 2 bytes
  450. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
  451. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0
  452. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
  453. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
  454. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  455. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
  456. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1 // 0xf0
  457. };
  458. static const char *XML_ByteTable=(const char *)XML_utf8ByteTable; // the default is "characterEncoding=XMLNode::encoding_UTF8"
  459. #endif
  460. XMLNode XMLNode::emptyXMLNode;
  461. XMLClear XMLNode::emptyXMLClear={ NULL, NULL, NULL};
  462. XMLAttribute XMLNode::emptyXMLAttribute={ NULL, NULL};
  463. // Enumeration used to decipher what type a token is
  464. typedef enum XMLTokenTypeTag
  465. {
  466. eTokenText = 0,
  467. eTokenQuotedText,
  468. eTokenTagStart, /* "<" */
  469. eTokenTagEnd, /* "</" */
  470. eTokenCloseTag, /* ">" */
  471. eTokenEquals, /* "=" */
  472. eTokenDeclaration, /* "<?" */
  473. eTokenShortHandClose, /* "/>" */
  474. eTokenClear,
  475. eTokenError
  476. } XMLTokenType;
  477. // Main structure used for parsing XML
  478. typedef struct XML
  479. {
  480. XMLCSTR lpXML;
  481. XMLCSTR lpszText;
  482. int nIndex,nIndexMissigEndTag;
  483. enum XMLError error;
  484. XMLCSTR lpEndTag;
  485. int cbEndTag;
  486. XMLCSTR lpNewElement;
  487. int cbNewElement;
  488. int nFirst;
  489. } XML;
  490. typedef struct
  491. {
  492. ALLXMLClearTag *pClr;
  493. XMLCSTR pStr;
  494. } NextToken;
  495. // Enumeration used when parsing attributes
  496. typedef enum Attrib
  497. {
  498. eAttribName = 0,
  499. eAttribEquals,
  500. eAttribValue
  501. } Attrib;
  502. // Enumeration used when parsing elements to dictate whether we are currently
  503. // inside a tag
  504. typedef enum Status
  505. {
  506. eInsideTag = 0,
  507. eOutsideTag
  508. } Status;
  509. XMLError XMLNode::writeToFile(XMLCSTR filename, const char *encoding, char nFormat) const
  510. {
  511. if (!d) return eXMLErrorNone;
  512. FILE *f=xfopen(filename,_CXML("wb"));
  513. if (!f) return eXMLErrorCannotOpenWriteFile;
  514. #ifdef _XMLWIDECHAR
  515. unsigned char h[2]={ 0xFF, 0xFE };
  516. if (!fwrite(h,2,1,f)) return eXMLErrorCannotWriteFile;
  517. if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
  518. {
  519. if (!fwrite(L"<?xml version=\"1.0\" encoding=\"utf-16\"?>\n",sizeof(wchar_t)*40,1,f))
  520. return eXMLErrorCannotWriteFile;
  521. }
  522. #else
  523. if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
  524. {
  525. if (characterEncoding==char_encoding_UTF8)
  526. {
  527. // header so that windows recognize the file as UTF-8:
  528. unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
  529. encoding="utf-8";
  530. } else if (characterEncoding==char_encoding_ShiftJIS) encoding="SHIFT-JIS";
  531. if (!encoding) encoding="ISO-8859-1";
  532. if (fprintf(f,"<?xml version=\"1.0\" encoding=\"%s\"?>\n",encoding)<0) return eXMLErrorCannotWriteFile;
  533. } else
  534. {
  535. if (characterEncoding==char_encoding_UTF8)
  536. {
  537. unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
  538. }
  539. }
  540. #endif
  541. int i;
  542. XMLSTR t=createXMLString(nFormat,&i);
  543. if (!fwrite(t,sizeof(XMLCHAR)*i,1,f)) return eXMLErrorCannotWriteFile;
  544. if (fclose(f)!=0) return eXMLErrorCannotWriteFile;
  545. free(t);
  546. return eXMLErrorNone;
  547. }
  548. // Duplicate a given string.
  549. XMLSTR stringDup(XMLCSTR lpszData, int cbData)
  550. {
  551. if (lpszData==NULL) return NULL;
  552. XMLSTR lpszNew;
  553. if (cbData==-1) cbData=(int)xstrlen(lpszData);
  554. lpszNew = (XMLSTR)malloc((cbData+1) * sizeof(XMLCHAR));
  555. if (lpszNew)
  556. {
  557. memcpy(lpszNew, lpszData, (cbData) * sizeof(XMLCHAR));
  558. lpszNew[cbData] = (XMLCHAR)NULL;
  559. }
  560. return lpszNew;
  561. }
  562. XMLSTR ToXMLStringTool::toXMLUnSafe(XMLSTR dest,XMLCSTR source)
  563. {
  564. XMLSTR dd=dest;
  565. XMLCHAR ch;
  566. XMLCharacterEntity *entity;
  567. while ((ch=*source))
  568. {
  569. entity=XMLEntities;
  570. do
  571. {
  572. if (ch==entity->c) {xstrcpy(dest,entity->s); dest+=entity->l; source++; goto out_of_loop1; }
  573. entity++;
  574. } while(entity->s);
  575. #ifdef _XMLWIDECHAR
  576. *(dest++)=*(source++);
  577. #else
  578. switch(XML_ByteTable[(unsigned char)ch])
  579. {
  580. case 4: *(dest++)=*(source++);
  581. case 3: *(dest++)=*(source++);
  582. case 2: *(dest++)=*(source++);
  583. case 1: *(dest++)=*(source++);
  584. }
  585. #endif
  586. out_of_loop1:
  587. ;
  588. }
  589. *dest=0;
  590. return dd;
  591. }
  592. // private (used while rendering):
  593. int ToXMLStringTool::lengthXMLString(XMLCSTR source)
  594. {
  595. int r=0;
  596. XMLCharacterEntity *entity;
  597. XMLCHAR ch;
  598. while ((ch=*source))
  599. {
  600. entity=XMLEntities;
  601. do
  602. {
  603. if (ch==entity->c) { r+=entity->l; source++; goto out_of_loop1; }
  604. entity++;
  605. } while(entity->s);
  606. #ifdef _XMLWIDECHAR
  607. r++; source++;
  608. #else
  609. ch=XML_ByteTable[(unsigned char)ch]; r+=ch; source+=ch;
  610. #endif
  611. out_of_loop1:
  612. ;
  613. }
  614. return r;
  615. }
  616. ToXMLStringTool::~ToXMLStringTool(){ freeBuffer(); }
  617. void ToXMLStringTool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; }
  618. XMLSTR ToXMLStringTool::toXML(XMLCSTR source)
  619. {
  620. int l=lengthXMLString(source)+1;
  621. if (l>buflen) { buflen=l; buf=(XMLSTR)realloc(buf,l*sizeof(XMLCHAR)); }
  622. return toXMLUnSafe(buf,source);
  623. }
  624. // private:
  625. XMLSTR fromXMLString(XMLCSTR s, int lo, XML *pXML)
  626. {
  627. // This function is the opposite of the function "toXMLString". It decodes the escape
  628. // sequences &amp;, &quot;, &apos;, &lt;, &gt; and replace them by the characters
  629. // &,",',<,>. This function is used internally by the XML Parser. All the calls to
  630. // the XML library will always gives you back "decoded" strings.
  631. //
  632. // in: string (s) and length (lo) of string
  633. // out: new allocated string converted from xml
  634. if (!s) return NULL;
  635. int ll=0,j;
  636. XMLSTR d;
  637. XMLCSTR ss=s;
  638. XMLCharacterEntity *entity;
  639. while ((lo>0)&&(*s))
  640. {
  641. if (*s==_CXML('&'))
  642. {
  643. if ((lo>2)&&(s[1]==_CXML('#')))
  644. {
  645. s+=2; lo-=2;
  646. if ((*s==_CXML('X'))||(*s==_CXML('x'))) { s++; lo--; }
  647. while ((*s)&&(*s!=_CXML(';'))&&((lo--)>0)) s++;
  648. if (*s!=_CXML(';'))
  649. {
  650. pXML->error=eXMLErrorUnknownCharacterEntity;
  651. return NULL;
  652. }
  653. s++; lo--;
  654. } else
  655. {
  656. entity=XMLEntities;
  657. do
  658. {
  659. if ((lo>=entity->l)&&(xstrnicmp(s,entity->s,entity->l)==0)) { s+=entity->l; lo-=entity->l; break; }
  660. entity++;
  661. } while(entity->s);
  662. if (!entity->s)
  663. {
  664. pXML->error=eXMLErrorUnknownCharacterEntity;
  665. return NULL;
  666. }
  667. }
  668. } else
  669. {
  670. #ifdef _XMLWIDECHAR
  671. s++; lo--;
  672. #else
  673. j=XML_ByteTable[(unsigned char)*s]; s+=j; lo-=j; ll+=j-1;
  674. #endif
  675. }
  676. ll++;
  677. }
  678. d=(XMLSTR)malloc((ll+1)*sizeof(XMLCHAR));
  679. s=d;
  680. while (ll-->0)
  681. {
  682. if (*ss==_CXML('&'))
  683. {
  684. if (ss[1]==_CXML('#'))
  685. {
  686. ss+=2; j=0;
  687. if ((*ss==_CXML('X'))||(*ss==_CXML('x')))
  688. {
  689. ss++;
  690. while (*ss!=_CXML(';'))
  691. {
  692. if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j<<4)+*ss-_CXML('0');
  693. else if ((*ss>=_CXML('A'))&&(*ss<=_CXML('F'))) j=(j<<4)+*ss-_CXML('A')+10;
  694. else if ((*ss>=_CXML('a'))&&(*ss<=_CXML('f'))) j=(j<<4)+*ss-_CXML('a')+10;
  695. else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
  696. ss++;
  697. }
  698. } else
  699. {
  700. while (*ss!=_CXML(';'))
  701. {
  702. if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j*10)+*ss-_CXML('0');
  703. else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
  704. ss++;
  705. }
  706. }
  707. #ifndef _XMLWIDECHAR
  708. if (j>255) { free((void*)s); pXML->error=eXMLErrorCharacterCodeAbove255;return NULL;}
  709. #endif
  710. (*d++)=(XMLCHAR)j; ss++;
  711. } else
  712. {
  713. entity=XMLEntities;
  714. do
  715. {
  716. if (xstrnicmp(ss,entity->s,entity->l)==0) { *(d++)=entity->c; ss+=entity->l; break; }
  717. entity++;
  718. } while(entity->s);
  719. }
  720. } else
  721. {
  722. #ifdef _XMLWIDECHAR
  723. *(d++)=*(ss++);
  724. #else
  725. switch(XML_ByteTable[(unsigned char)*ss])
  726. {
  727. case 4: *(d++)=*(ss++); ll--;
  728. case 3: *(d++)=*(ss++); ll--;
  729. case 2: *(d++)=*(ss++); ll--;
  730. case 1: *(d++)=*(ss++);
  731. }
  732. #endif
  733. }
  734. }
  735. *d=0;
  736. return (XMLSTR)s;
  737. }
  738. #define XML_isSPACECHAR(ch) ((ch==_CXML('\n'))||(ch==_CXML(' '))||(ch== _CXML('\t'))||(ch==_CXML('\r')))
  739. // private:
  740. char myTagCompare(XMLCSTR cclose, XMLCSTR copen)
  741. // !!!! WARNING strange convention&:
  742. // return 0 if equals
  743. // return 1 if different
  744. {
  745. if (!cclose) return 1;
  746. int l=(int)xstrlen(cclose);
  747. if (xstrnicmp(cclose, copen, l)!=0) return 1;
  748. const XMLCHAR c=copen[l];
  749. if (XML_isSPACECHAR(c)||
  750. (c==_CXML('/' ))||
  751. (c==_CXML('<' ))||
  752. (c==_CXML('>' ))||
  753. (c==_CXML('=' ))) return 0;
  754. return 1;
  755. }
  756. // Obtain the next character from the string.
  757. static inline XMLCHAR getNextChar(XML *pXML)
  758. {
  759. XMLCHAR ch = pXML->lpXML[pXML->nIndex];
  760. #ifdef _XMLWIDECHAR
  761. if (ch!=0) pXML->nIndex++;
  762. #else
  763. pXML->nIndex+=XML_ByteTable[(unsigned char)ch];
  764. #endif
  765. return ch;
  766. }
  767. // Find the next token in a string.
  768. // pcbToken contains the number of characters that have been read.
  769. static NextToken GetNextToken(XML *pXML, int *pcbToken, enum XMLTokenTypeTag *pType)
  770. {
  771. NextToken result;
  772. XMLCHAR ch;
  773. XMLCHAR chTemp;
  774. int indexStart,nFoundMatch,nIsText=FALSE;
  775. result.pClr=NULL; // prevent warning
  776. // Find next non-white space character
  777. do { indexStart=pXML->nIndex; ch=getNextChar(pXML); } while XML_isSPACECHAR(ch);
  778. if (ch)
  779. {
  780. // Cache the current string pointer
  781. result.pStr = &pXML->lpXML[indexStart];
  782. // First check whether the token is in the clear tag list (meaning it
  783. // does not need formatting).
  784. ALLXMLClearTag *ctag=XMLClearTags;
  785. do
  786. {
  787. if (xstrncmp(ctag->lpszOpen, result.pStr, ctag->openTagLen)==0)
  788. {
  789. result.pClr=ctag;
  790. pXML->nIndex+=ctag->openTagLen-1;
  791. *pType=eTokenClear;
  792. return result;
  793. }
  794. ctag++;
  795. } while(ctag->lpszOpen);
  796. // If we didn't find a clear tag then check for standard tokens
  797. switch(ch)
  798. {
  799. // Check for quotes
  800. case _CXML('\''):
  801. case _CXML('\"'):
  802. // Type of token
  803. *pType = eTokenQuotedText;
  804. chTemp = ch;
  805. // Set the size
  806. nFoundMatch = FALSE;
  807. // Search through the string to find a matching quote
  808. while((ch = getNextChar(pXML)))
  809. {
  810. if (ch==chTemp) { nFoundMatch = TRUE; break; }
  811. if (ch==_CXML('<')) break;
  812. }
  813. // If we failed to find a matching quote
  814. if (nFoundMatch == FALSE)
  815. {
  816. pXML->nIndex=indexStart+1;
  817. nIsText=TRUE;
  818. break;
  819. }
  820. // 4.02.2002
  821. // if (FindNonWhiteSpace(pXML)) pXML->nIndex--;
  822. break;
  823. // Equals (used with attribute values)
  824. case _CXML('='):
  825. *pType = eTokenEquals;
  826. break;
  827. // Close tag
  828. case _CXML('>'):
  829. *pType = eTokenCloseTag;
  830. break;
  831. // Check for tag start and tag end
  832. case _CXML('<'):
  833. // Peek at the next character to see if we have an end tag '</',
  834. // or an xml declaration '<?'
  835. chTemp = pXML->lpXML[pXML->nIndex];
  836. // If we have a tag end...
  837. if (chTemp == _CXML('/'))
  838. {
  839. // Set the type and ensure we point at the next character
  840. getNextChar(pXML);
  841. *pType = eTokenTagEnd;
  842. }
  843. // If we have an XML declaration tag
  844. else if (chTemp == _CXML('?'))
  845. {
  846. // Set the type and ensure we point at the next character
  847. getNextChar(pXML);
  848. *pType = eTokenDeclaration;
  849. }
  850. // Otherwise we must have a start tag
  851. else
  852. {
  853. *pType = eTokenTagStart;
  854. }
  855. break;
  856. // Check to see if we have a short hand type end tag ('/>').
  857. case _CXML('/'):
  858. // Peek at the next character to see if we have a short end tag '/>'
  859. chTemp = pXML->lpXML[pXML->nIndex];
  860. // If we have a short hand end tag...
  861. if (chTemp == _CXML('>'))
  862. {
  863. // Set the type and ensure we point at the next character
  864. getNextChar(pXML);
  865. *pType = eTokenShortHandClose;
  866. break;
  867. }
  868. // If we haven't found a short hand closing tag then drop into the
  869. // text process
  870. // Other characters
  871. default:
  872. nIsText = TRUE;
  873. }
  874. // If this is a TEXT node
  875. if (nIsText)
  876. {
  877. // Indicate we are dealing with text
  878. *pType = eTokenText;
  879. while((ch = getNextChar(pXML)))
  880. {
  881. if XML_isSPACECHAR(ch)
  882. {
  883. indexStart++; break;
  884. } else if (ch==_CXML('/'))
  885. {
  886. // If we find a slash then this maybe text or a short hand end tag
  887. // Peek at the next character to see it we have short hand end tag
  888. ch=pXML->lpXML[pXML->nIndex];
  889. // If we found a short hand end tag then we need to exit the loop
  890. if (ch==_CXML('>')) { pXML->nIndex--; break; }
  891. } else if ((ch==_CXML('<'))||(ch==_CXML('>'))||(ch==_CXML('=')))
  892. {
  893. pXML->nIndex--; break;
  894. }
  895. }
  896. }
  897. *pcbToken = pXML->nIndex-indexStart;
  898. } else
  899. {
  900. // If we failed to obtain a valid character
  901. *pcbToken = 0;
  902. *pType = eTokenError;
  903. result.pStr=NULL;
  904. }
  905. return result;
  906. }
  907. XMLCSTR XMLNode::updateName_WOSD(XMLSTR lpszName)
  908. {
  909. if (!d) { free(lpszName); return NULL; }
  910. if (d->lpszName&&(lpszName!=d->lpszName)) free((void*)d->lpszName);
  911. d->lpszName=lpszName;
  912. return lpszName;
  913. }
  914. // private:
  915. XMLNode::XMLNode(struct XMLNodeDataTag *p){ d=p; (p->ref_count)++; }
  916. XMLNode::XMLNode(XMLNodeData *pParent, XMLSTR lpszName, char isDeclaration)
  917. {
  918. d=(XMLNodeData*)malloc(sizeof(XMLNodeData));
  919. d->ref_count=1;
  920. d->lpszName=NULL;
  921. d->nChild= 0;
  922. d->nText = 0;
  923. d->nClear = 0;
  924. d->nAttribute = 0;
  925. d->isDeclaration = isDeclaration;
  926. d->pParent = pParent;
  927. d->pChild= NULL;
  928. d->pText= NULL;
  929. d->pClear= NULL;
  930. d->pAttribute= NULL;
  931. d->pOrder= NULL;
  932. updateName_WOSD(lpszName);
  933. }
  934. XMLNode XMLNode::createXMLTopNode_WOSD(XMLSTR lpszName, char isDeclaration) { return XMLNode(NULL,lpszName,isDeclaration); }
  935. XMLNode XMLNode::createXMLTopNode(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,stringDup(lpszName),isDeclaration); }
  936. #define MEMORYINCREASE 50
  937. static inline void myFree(void *p) { if (p) free(p); }
  938. static inline void *myRealloc(void *p, int newsize, int memInc, int sizeofElem)
  939. {
  940. if (p==NULL) { if (memInc) return malloc(memInc*sizeofElem); return malloc(sizeofElem); }
  941. if ((memInc==0)||((newsize%memInc)==0)) p=realloc(p,(newsize+memInc)*sizeofElem);
  942. // if (!p)
  943. // {
  944. // printf("XMLParser Error: Not enough memory! Aborting...\n"); exit(220);
  945. // }
  946. return p;
  947. }
  948. // private:
  949. XMLElementPosition XMLNode::findPosition(XMLNodeData *d, int index, XMLElementType xxtype)
  950. {
  951. if (index<0) return -1;
  952. int i=0,j=(int)((index<<2)+xxtype),*o=d->pOrder; while (o[i]!=j) i++; return i;
  953. }
  954. // private:
  955. // update "order" information when deleting a content of a XMLNode
  956. int XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index)
  957. {
  958. int n=d->nChild+d->nText+d->nClear, *o=d->pOrder,i=findPosition(d,index,t);
  959. memmove(o+i, o+i+1, (n-i)*sizeof(int));
  960. for (;i<n;i++)
  961. if ((o[i]&3)==(int)t) o[i]-=4;
  962. // We should normally do:
  963. // d->pOrder=(int)realloc(d->pOrder,n*sizeof(int));
  964. // but we skip reallocation because it's too time consuming.
  965. // Anyway, at the end, it will be free'd completely at once.
  966. return i;
  967. }
  968. void *XMLNode::addToOrder(int memoryIncrease,int *_pos, int nc, void *p, int size, XMLElementType xtype)
  969. {
  970. // in: *_pos is the position inside d->pOrder ("-1" means "EndOf")
  971. // out: *_pos is the index inside p
  972. p=myRealloc(p,(nc+1),memoryIncrease,size);
  973. int n=d->nChild+d->nText+d->nClear;
  974. d->pOrder=(int*)myRealloc(d->pOrder,n+1,memoryIncrease*3,sizeof(int));
  975. int pos=*_pos,*o=d->pOrder;
  976. if ((pos<0)||(pos>=n)) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
  977. int i=pos;
  978. memmove(o+i+1, o+i, (n-i)*sizeof(int));
  979. while ((pos<n)&&((o[pos]&3)!=(int)xtype)) pos++;
  980. if (pos==n) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
  981. o[i]=o[pos];
  982. for (i=pos+1;i<=n;i++) if ((o[i]&3)==(int)xtype) o[i]+=4;
  983. *_pos=pos=o[pos]>>2;
  984. memmove(((char*)p)+(pos+1)*size,((char*)p)+pos*size,(nc-pos)*size);
  985. return p;
  986. }
  987. // Add a child node to the given element.
  988. XMLNode XMLNode::addChild_priv(int memoryIncrease, XMLSTR lpszName, char isDeclaration, int pos)
  989. {
  990. if (!lpszName) return emptyXMLNode;
  991. d->pChild=(XMLNode*)addToOrder(memoryIncrease,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
  992. d->pChild[pos].d=NULL;
  993. d->pChild[pos]=XMLNode(d,lpszName,isDeclaration);
  994. d->nChild++;
  995. return d->pChild[pos];
  996. }
  997. // Add an attribute to an element.
  998. XMLAttribute *XMLNode::addAttribute_priv(int memoryIncrease,XMLSTR lpszName, XMLSTR lpszValuev)
  999. {
  1000. if (!lpszName) return &emptyXMLAttribute;
  1001. if (!d) { myFree(lpszName); myFree(lpszValuev); return &emptyXMLAttribute; }
  1002. int nc=d->nAttribute;
  1003. d->pAttribute=(XMLAttribute*)myRealloc(d->pAttribute,(nc+1),memoryIncrease,sizeof(XMLAttribute));
  1004. XMLAttribute *pAttr=d->pAttribute+nc;
  1005. pAttr->lpszName = lpszName;
  1006. pAttr->lpszValue = lpszValuev;
  1007. d->nAttribute++;
  1008. return pAttr;
  1009. }
  1010. // Add text to the element.
  1011. XMLCSTR XMLNode::addText_priv(int memoryIncrease, XMLSTR lpszValue, int pos)
  1012. {
  1013. if (!lpszValue) return NULL;
  1014. if (!d) { myFree(lpszValue); return NULL; }
  1015. d->pText=(XMLCSTR*)addToOrder(memoryIncrease,&pos,d->nText,d->pText,sizeof(XMLSTR),eNodeText);
  1016. d->pText[pos]=lpszValue;
  1017. d->nText++;
  1018. return lpszValue;
  1019. }
  1020. // Add clear (unformatted) text to the element.
  1021. XMLClear *XMLNode::addClear_priv(int memoryIncrease, XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
  1022. {
  1023. if (!lpszValue) return &emptyXMLClear;
  1024. if (!d) { myFree(lpszValue); return &emptyXMLClear; }
  1025. d->pClear=(XMLClear *)addToOrder(memoryIncrease,&pos,d->nClear,d->pClear,sizeof(XMLClear),eNodeClear);
  1026. XMLClear *pNewClear=d->pClear+pos;
  1027. pNewClear->lpszValue = lpszValue;
  1028. if (!lpszOpen) lpszOpen=XMLClearTags->lpszOpen;
  1029. if (!lpszClose) lpszClose=XMLClearTags->lpszClose;
  1030. pNewClear->lpszOpenTag = lpszOpen;
  1031. pNewClear->lpszCloseTag = lpszClose;
  1032. d->nClear++;
  1033. return pNewClear;
  1034. }
  1035. // private:
  1036. // Parse a clear (unformatted) type node.
  1037. char XMLNode::parseClearTag(void *px, void *_pClear)
  1038. {
  1039. XML *pXML=(XML *)px;
  1040. ALLXMLClearTag pClear=*((ALLXMLClearTag*)_pClear);
  1041. int cbTemp=0;
  1042. XMLCSTR lpszTemp=NULL;
  1043. XMLCSTR lpXML=&pXML->lpXML[pXML->nIndex];
  1044. static XMLCSTR docTypeEnd=_CXML("]>");
  1045. // Find the closing tag
  1046. // Seems the <!DOCTYPE need a better treatment so lets handle it
  1047. if (pClear.lpszOpen==XMLClearTags[1].lpszOpen)
  1048. {
  1049. XMLCSTR pCh=lpXML;
  1050. while (*pCh)
  1051. {
  1052. if (*pCh==_CXML('<')) { pClear.lpszClose=docTypeEnd; lpszTemp=xstrstr(lpXML,docTypeEnd); break; }
  1053. else if (*pCh==_CXML('>')) { lpszTemp=pCh; break; }
  1054. #ifdef _XMLWIDECHAR
  1055. pCh++;
  1056. #else
  1057. pCh+=XML_ByteTable[(unsigned char)(*pCh)];
  1058. #endif
  1059. }
  1060. } else lpszTemp=xstrstr(lpXML, pClear.lpszClose);
  1061. if (lpszTemp)
  1062. {
  1063. // Cache the size and increment the index
  1064. cbTemp = (int)(lpszTemp - lpXML);
  1065. pXML->nIndex += cbTemp+(int)xstrlen(pClear.lpszClose);
  1066. // Add the clear node to the current element
  1067. addClear_priv(MEMORYINCREASE,stringDup(lpXML,cbTemp), pClear.lpszOpen, pClear.lpszClose,-1);
  1068. return 0;
  1069. }
  1070. // If we failed to find the end tag
  1071. pXML->error = eXMLErrorUnmatchedEndClearTag;
  1072. return 1;
  1073. }
  1074. void XMLNode::exactMemory(XMLNodeData *d)
  1075. {
  1076. if (d->pOrder) d->pOrder=(int*)realloc(d->pOrder,(d->nChild+d->nText+d->nClear)*sizeof(int));
  1077. if (d->pChild) d->pChild=(XMLNode*)realloc(d->pChild,d->nChild*sizeof(XMLNode));
  1078. if (d->pAttribute) d->pAttribute=(XMLAttribute*)realloc(d->pAttribute,d->nAttribute*sizeof(XMLAttribute));
  1079. if (d->pText) d->pText=(XMLCSTR*)realloc(d->pText,d->nText*sizeof(XMLSTR));
  1080. if (d->pClear) d->pClear=(XMLClear *)realloc(d->pClear,d->nClear*sizeof(XMLClear));
  1081. }
  1082. char XMLNode::maybeAddTxT(void *pa, XMLCSTR tokenPStr)
  1083. {
  1084. XML *pXML=(XML *)pa;
  1085. XMLCSTR lpszText=pXML->lpszText;
  1086. if (!lpszText) return 0;
  1087. if (dropWhiteSpace) while (XML_isSPACECHAR(*lpszText)&&(lpszText!=tokenPStr)) lpszText++;
  1088. int cbText = (int)(tokenPStr - lpszText);
  1089. if (!cbText) { pXML->lpszText=NULL; return 0; }
  1090. if (dropWhiteSpace) { cbText--; while ((cbText)&&XML_isSPACECHAR(lpszText[cbText])) cbText--; cbText++; }
  1091. if (!cbText) { pXML->lpszText=NULL; return 0; }
  1092. XMLSTR lpt=fromXMLString(lpszText,cbText,pXML);
  1093. if (!lpt) return 1;
  1094. pXML->lpszText=NULL;
  1095. if (removeCommentsInMiddleOfText && d->nText && d->nClear)
  1096. {
  1097. // if the previous insertion was a comment (<!-- -->) AND
  1098. // if the previous previous insertion was a text then, delete the comment and append the text
  1099. int n=d->nChild+d->nText+d->nClear-1,*o=d->pOrder;
  1100. if (((o[n]&3)==eNodeClear)&&((o[n-1]&3)==eNodeText))
  1101. {
  1102. int i=o[n]>>2;
  1103. if (d->pClear[i].lpszOpenTag==XMLClearTags[2].lpszOpen)
  1104. {
  1105. deleteClear(i);
  1106. i=o[n-1]>>2;
  1107. n=xstrlen(d->pText[i]);
  1108. int n2=xstrlen(lpt)+1;
  1109. d->pText[i]=(XMLSTR)realloc((void*)d->pText[i],(n+n2)*sizeof(XMLCHAR));
  1110. if (!d->pText[i]) return 1;
  1111. memcpy((void*)(d->pText[i]+n),lpt,n2*sizeof(XMLCHAR));
  1112. free(lpt);
  1113. return 0;
  1114. }
  1115. }
  1116. }
  1117. addText_priv(MEMORYINCREASE,lpt,-1);
  1118. return 0;
  1119. }
  1120. // private:
  1121. // Recursively parse an XML element.
  1122. int XMLNode::ParseXMLElement(void *pa)
  1123. {
  1124. XML *pXML=(XML *)pa;
  1125. int cbToken;
  1126. enum XMLTokenTypeTag xtype;
  1127. NextToken token;
  1128. XMLCSTR lpszTemp=NULL;
  1129. int cbTemp=0;
  1130. char nDeclaration;
  1131. XMLNode pNew;
  1132. enum Status status; // inside or outside a tag
  1133. enum Attrib attrib = eAttribName;
  1134. assert(pXML);
  1135. // If this is the first call to the function
  1136. if (pXML->nFirst)
  1137. {
  1138. // Assume we are outside of a tag definition
  1139. pXML->nFirst = FALSE;
  1140. status = eOutsideTag;
  1141. } else
  1142. {
  1143. // If this is not the first call then we should only be called when inside a tag.
  1144. status = eInsideTag;
  1145. }
  1146. // Iterate through the tokens in the document
  1147. for(;;)
  1148. {
  1149. // Obtain the next token
  1150. token = GetNextToken(pXML, &cbToken, &xtype);
  1151. if (xtype != eTokenError)
  1152. {
  1153. // Check the current status
  1154. switch(status)
  1155. {
  1156. // If we are outside of a tag definition
  1157. case eOutsideTag:
  1158. // Check what type of token we obtained
  1159. switch(xtype)
  1160. {
  1161. // If we have found text or quoted text
  1162. case eTokenText:
  1163. case eTokenCloseTag: /* '>' */
  1164. case eTokenShortHandClose: /* '/>' */
  1165. case eTokenQuotedText:
  1166. case eTokenEquals:
  1167. break;
  1168. // If we found a start tag '<' and declarations '<?'
  1169. case eTokenTagStart:
  1170. case eTokenDeclaration:
  1171. // Cache whether this new element is a declaration or not
  1172. nDeclaration = (xtype == eTokenDeclaration);
  1173. // If we have node text then add this to the element
  1174. if (maybeAddTxT(pXML,token.pStr)) return FALSE;
  1175. // Find the name of the tag
  1176. token = GetNextToken(pXML, &cbToken, &xtype);
  1177. // Return an error if we couldn't obtain the next token or
  1178. // it wasnt text
  1179. if (xtype != eTokenText)
  1180. {
  1181. pXML->error = eXMLErrorMissingTagName;
  1182. return FALSE;
  1183. }
  1184. // If we found a new element which is the same as this
  1185. // element then we need to pass this back to the caller..
  1186. #ifdef APPROXIMATE_PARSING
  1187. if (d->lpszName &&
  1188. myTagCompare(d->lpszName, token.pStr) == 0)
  1189. {
  1190. // Indicate to the caller that it needs to create a
  1191. // new element.
  1192. pXML->lpNewElement = token.pStr;
  1193. pXML->cbNewElement = cbToken;
  1194. return TRUE;
  1195. } else
  1196. #endif
  1197. {
  1198. // If the name of the new element differs from the name of
  1199. // the current element we need to add the new element to
  1200. // the current one and recurse
  1201. pNew = addChild_priv(MEMORYINCREASE,stringDup(token.pStr,cbToken), nDeclaration,-1);
  1202. while (!pNew.isEmpty())
  1203. {
  1204. // Callself to process the new node. If we return
  1205. // FALSE this means we dont have any more
  1206. // processing to do...
  1207. if (!pNew.ParseXMLElement(pXML)) return FALSE;
  1208. else
  1209. {
  1210. // If the call to recurse this function
  1211. // evented in a end tag specified in XML then
  1212. // we need to unwind the calls to this
  1213. // function until we find the appropriate node
  1214. // (the element name and end tag name must
  1215. // match)
  1216. if (pXML->cbEndTag)
  1217. {
  1218. // If we are back at the root node then we
  1219. // have an unmatched end tag
  1220. if (!d->lpszName)
  1221. {
  1222. pXML->error=eXMLErrorUnmatchedEndTag;
  1223. return FALSE;
  1224. }
  1225. // If the end tag matches the name of this
  1226. // element then we only need to unwind
  1227. // once more...
  1228. if (myTagCompare(d->lpszName, pXML->lpEndTag)==0)
  1229. {
  1230. pXML->cbEndTag = 0;
  1231. }
  1232. return TRUE;
  1233. } else
  1234. if (pXML->cbNewElement)
  1235. {
  1236. // If the call indicated a new element is to
  1237. // be created on THIS element.
  1238. // If the name of this element matches the
  1239. // name of the element we need to create
  1240. // then we need to return to the caller
  1241. // and let it process the element.
  1242. if (myTagCompare(d->lpszName, pXML->lpNewElement)==0)
  1243. {
  1244. return TRUE;
  1245. }
  1246. // Add the new element and recurse
  1247. pNew = addChild_priv(MEMORYINCREASE,stringDup(pXML->lpNewElement,pXML->cbNewElement),0,-1);
  1248. pXML->cbNewElement = 0;
  1249. }
  1250. else
  1251. {
  1252. // If we didn't have a new element to create
  1253. pNew = emptyXMLNode;
  1254. }
  1255. }
  1256. }
  1257. }
  1258. break;
  1259. // If we found an end tag
  1260. case eTokenTagEnd:
  1261. // If we have node text then add this to the element
  1262. if (maybeAddTxT(pXML,token.pStr)) return FALSE;
  1263. // Find the name of the end tag
  1264. token = GetNextToken(pXML, &cbTemp, &xtype);
  1265. // The end tag should be text
  1266. if (xtype != eTokenText)
  1267. {
  1268. pXML->error = eXMLErrorMissingEndTagName;
  1269. return FALSE;
  1270. }
  1271. lpszTemp = token.pStr;
  1272. // After the end tag we should find a closing tag
  1273. token = GetNextToken(pXML, &cbToken, &xtype);
  1274. if (xtype != eTokenCloseTag)
  1275. {
  1276. pXML->error = eXMLErrorMissingEndTagName;
  1277. return FALSE;
  1278. }
  1279. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1280. // We need to return to the previous caller. If the name
  1281. // of the tag cannot be found we need to keep returning to
  1282. // caller until we find a match
  1283. if (myTagCompare(d->lpszName, lpszTemp) != 0)
  1284. #ifdef STRICT_PARSING
  1285. {
  1286. pXML->error=eXMLErrorUnmatchedEndTag;
  1287. pXML->nIndexMissigEndTag=pXML->nIndex;
  1288. return FALSE;
  1289. }
  1290. #else
  1291. {
  1292. pXML->error=eXMLErrorMissingEndTag;
  1293. pXML->nIndexMissigEndTag=pXML->nIndex;
  1294. pXML->lpEndTag = lpszTemp;
  1295. pXML->cbEndTag = cbTemp;
  1296. }
  1297. #endif
  1298. // Return to the caller
  1299. exactMemory(d);
  1300. return TRUE;
  1301. // If we found a clear (unformatted) token
  1302. case eTokenClear:
  1303. // If we have node text then add this to the element
  1304. if (maybeAddTxT(pXML,token.pStr)) return FALSE;
  1305. if (parseClearTag(pXML, token.pClr)) return FALSE;
  1306. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1307. break;
  1308. default:
  1309. break;
  1310. }
  1311. break;
  1312. // If we are inside a tag definition we need to search for attributes
  1313. case eInsideTag:
  1314. // Check what part of the attribute (name, equals, value) we
  1315. // are looking for.
  1316. switch(attrib)
  1317. {
  1318. // If we are looking for a new attribute
  1319. case eAttribName:
  1320. // Check what the current token type is
  1321. switch(xtype)
  1322. {
  1323. // If the current type is text...
  1324. // Eg. 'attribute'
  1325. case eTokenText:
  1326. // Cache the token then indicate that we are next to
  1327. // look for the equals
  1328. lpszTemp = token.pStr;
  1329. cbTemp = cbToken;
  1330. attrib = eAttribEquals;
  1331. break;
  1332. // If we found a closing tag...
  1333. // Eg. '>'
  1334. case eTokenCloseTag:
  1335. // We are now outside the tag
  1336. status = eOutsideTag;
  1337. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1338. break;
  1339. // If we found a short hand '/>' closing tag then we can
  1340. // return to the caller
  1341. case eTokenShortHandClose:
  1342. exactMemory(d);
  1343. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1344. return TRUE;
  1345. // Errors...
  1346. case eTokenQuotedText: /* '"SomeText"' */
  1347. case eTokenTagStart: /* '<' */
  1348. case eTokenTagEnd: /* '</' */
  1349. case eTokenEquals: /* '=' */
  1350. case eTokenDeclaration: /* '<?' */
  1351. case eTokenClear:
  1352. pXML->error = eXMLErrorUnexpectedToken;
  1353. return FALSE;
  1354. default: break;
  1355. }
  1356. break;
  1357. // If we are looking for an equals
  1358. case eAttribEquals:
  1359. // Check what the current token type is
  1360. switch(xtype)
  1361. {
  1362. // If the current type is text...
  1363. // Eg. 'Attribute AnotherAttribute'
  1364. case eTokenText:
  1365. // Add the unvalued attribute to the list
  1366. addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
  1367. // Cache the token then indicate. We are next to
  1368. // look for the equals attribute
  1369. lpszTemp = token.pStr;
  1370. cbTemp = cbToken;
  1371. break;
  1372. // If we found a closing tag 'Attribute >' or a short hand
  1373. // closing tag 'Attribute />'
  1374. case eTokenShortHandClose:
  1375. case eTokenCloseTag:
  1376. // If we are a declaration element '<?' then we need
  1377. // to remove extra closing '?' if it exists
  1378. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1379. if (d->isDeclaration &&
  1380. (lpszTemp[cbTemp-1]) == _CXML('?'))
  1381. {
  1382. cbTemp--;
  1383. if (d->pParent && d->pParent->pParent) xtype = eTokenShortHandClose;
  1384. }
  1385. if (cbTemp)
  1386. {
  1387. // Add the unvalued attribute to the list
  1388. addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
  1389. }
  1390. // If this is the end of the tag then return to the caller
  1391. if (xtype == eTokenShortHandClose)
  1392. {
  1393. exactMemory(d);
  1394. return TRUE;
  1395. }
  1396. // We are now outside the tag
  1397. status = eOutsideTag;
  1398. break;
  1399. // If we found the equals token...
  1400. // Eg. 'Attribute ='
  1401. case eTokenEquals:
  1402. // Indicate that we next need to search for the value
  1403. // for the attribute
  1404. attrib = eAttribValue;
  1405. break;
  1406. // Errors...
  1407. case eTokenQuotedText: /* 'Attribute "InvalidAttr"'*/
  1408. case eTokenTagStart: /* 'Attribute <' */
  1409. case eTokenTagEnd: /* 'Attribute </' */
  1410. case eTokenDeclaration: /* 'Attribute <?' */
  1411. case eTokenClear:
  1412. pXML->error = eXMLErrorUnexpectedToken;
  1413. return FALSE;
  1414. default: break;
  1415. }
  1416. break;
  1417. // If we are looking for an attribute value
  1418. case eAttribValue:
  1419. // Check what the current token type is
  1420. switch(xtype)
  1421. {
  1422. // If the current type is text or quoted text...
  1423. // Eg. 'Attribute = "Value"' or 'Attribute = Value' or
  1424. // 'Attribute = 'Value''.
  1425. case eTokenText:
  1426. case eTokenQuotedText:
  1427. // If we are a declaration element '<?' then we need
  1428. // to remove extra closing '?' if it exists
  1429. if (d->isDeclaration &&
  1430. (token.pStr[cbToken-1]) == _CXML('?'))
  1431. {
  1432. cbToken--;
  1433. }
  1434. if (cbTemp)
  1435. {
  1436. // Add the valued attribute to the list
  1437. if (xtype==eTokenQuotedText) { token.pStr++; cbToken-=2; }
  1438. XMLSTR attrVal=(XMLSTR)token.pStr;
  1439. if (attrVal)
  1440. {
  1441. attrVal=fromXMLString(attrVal,cbToken,pXML);
  1442. if (!attrVal) return FALSE;
  1443. }
  1444. addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp),attrVal);
  1445. }
  1446. // Indicate we are searching for a new attribute
  1447. attrib = eAttribName;
  1448. break;
  1449. // Errors...
  1450. case eTokenTagStart: /* 'Attr = <' */
  1451. case eTokenTagEnd: /* 'Attr = </' */
  1452. case eTokenCloseTag: /* 'Attr = >' */
  1453. case eTokenShortHandClose: /* "Attr = />" */
  1454. case eTokenEquals: /* 'Attr = =' */
  1455. case eTokenDeclaration: /* 'Attr = <?' */
  1456. case eTokenClear:
  1457. pXML->error = eXMLErrorUnexpectedToken;
  1458. return FALSE;
  1459. break;
  1460. default: break;
  1461. }
  1462. }
  1463. }
  1464. }
  1465. // If we failed to obtain the next token
  1466. else
  1467. {
  1468. if ((!d->isDeclaration)&&(d->pParent))
  1469. {
  1470. #ifdef STRICT_PARSING
  1471. pXML->error=eXMLErrorUnmatchedEndTag;
  1472. #else
  1473. pXML->error=eXMLErrorMissingEndTag;
  1474. #endif
  1475. pXML->nIndexMissigEndTag=pXML->nIndex;
  1476. }
  1477. maybeAddTxT(pXML,pXML->lpXML+pXML->nIndex);
  1478. return FALSE;
  1479. }
  1480. }
  1481. }
  1482. // Count the number of lines and columns in an XML string.
  1483. static void CountLinesAndColumns(XMLCSTR lpXML, int nUpto, XMLResults *pResults)
  1484. {
  1485. XMLCHAR ch;
  1486. assert(lpXML);
  1487. assert(pResults);
  1488. struct XML xml={ lpXML,lpXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
  1489. pResults->nLine = 1;
  1490. pResults->nColumn = 1;
  1491. while (xml.nIndex<nUpto)
  1492. {
  1493. ch = getNextChar(&xml);
  1494. if (ch != _CXML('\n')) pResults->nColumn++;
  1495. else
  1496. {
  1497. pResults->nLine++;
  1498. pResults->nColumn=1;
  1499. }
  1500. }
  1501. }
  1502. // Parse XML and return the root element.
  1503. XMLNode XMLNode::parseString(XMLCSTR lpszXML, XMLCSTR tag, XMLResults *pResults)
  1504. {
  1505. if (!lpszXML)
  1506. {
  1507. if (pResults)
  1508. {
  1509. pResults->error=eXMLErrorNoElements;
  1510. pResults->nLine=0;
  1511. pResults->nColumn=0;
  1512. }
  1513. return emptyXMLNode;
  1514. }
  1515. XMLNode xnode(NULL,NULL,FALSE);
  1516. struct XML xml={ lpszXML, lpszXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
  1517. // Create header element
  1518. xnode.ParseXMLElement(&xml);
  1519. enum XMLError error = xml.error;
  1520. if (!xnode.nChildNode()) error=eXMLErrorNoXMLTagFound;
  1521. if ((xnode.nChildNode()==1)&&(xnode.nElement()==1)) xnode=xnode.getChildNode(); // skip the empty node
  1522. // If no error occurred
  1523. if ((error==eXMLErrorNone)||(error==eXMLErrorMissingEndTag)||(error==eXMLErrorNoXMLTagFound))
  1524. {
  1525. XMLCSTR name=xnode.getName();
  1526. if (tag&&(*tag)&&((!name)||(xstricmp(name,tag))))
  1527. {
  1528. xnode=xnode.getChildNode(tag);
  1529. if (xnode.isEmpty())
  1530. {
  1531. if (pResults)
  1532. {
  1533. pResults->error=eXMLErrorFirstTagNotFound;
  1534. pResults->nLine=0;
  1535. pResults->nColumn=0;
  1536. }
  1537. return emptyXMLNode;
  1538. }
  1539. }
  1540. } else
  1541. {
  1542. // Cleanup: this will destroy all the nodes
  1543. xnode = emptyXMLNode;
  1544. }
  1545. // If we have been given somewhere to place results
  1546. if (pResults)
  1547. {
  1548. pResults->error = error;
  1549. // If we have an error
  1550. if (error!=eXMLErrorNone)
  1551. {
  1552. if (error==eXMLErrorMissingEndTag) xml.nIndex=xml.nIndexMissigEndTag;
  1553. // Find which line and column it starts on.
  1554. CountLinesAndColumns(xml.lpXML, xml.nIndex, pResults);
  1555. }
  1556. }
  1557. return xnode;
  1558. }
  1559. XMLNode XMLNode::parseFile(XMLCSTR filename, XMLCSTR tag, XMLResults *pResults)
  1560. {
  1561. if (pResults) { pResults->nLine=0; pResults->nColumn=0; }
  1562. FILE *f=xfopen(filename,_CXML("rb"));
  1563. if (f==NULL) { if (pResults) pResults->error=eXMLErrorFileNotFound; return emptyXMLNode; }
  1564. fseek(f,0,SEEK_END);
  1565. int l=ftell(f),headerSz=0;
  1566. if (!l) { if (pResults) pResults->error=eXMLErrorEmpty; fclose(f); return emptyXMLNode; }
  1567. fseek(f,0,SEEK_SET);
  1568. unsigned char *buf=(unsigned char*)malloc(l+4);
  1569. int really_read = (int)fread(buf,1,l,f); // JLBC
  1570. if (really_read!=l) buf[0]='\0';
  1571. fclose(f);
  1572. buf[l]=0;buf[l+1]=0;buf[l+2]=0;buf[l+3]=0;
  1573. #ifdef _XMLWIDECHAR
  1574. if (guessWideCharChars)
  1575. {
  1576. if (!myIsTextWideChar(buf,l))
  1577. {
  1578. XMLNode::XMLCharEncoding ce=XMLNode::char_encoding_legacy;
  1579. if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) { headerSz=3; ce=XMLNode::char_encoding_UTF8; }
  1580. XMLSTR b2=myMultiByteToWideChar((const char*)(buf+headerSz),ce);
  1581. free(buf); buf=(unsigned char*)b2; headerSz=0;
  1582. } else
  1583. {
  1584. if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
  1585. if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
  1586. }
  1587. }
  1588. #else
  1589. if (guessWideCharChars)
  1590. {
  1591. if (myIsTextWideChar(buf,l))
  1592. {
  1593. if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
  1594. if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
  1595. char *b2=myWideCharToMultiByte((const wchar_t*)(buf+headerSz));
  1596. free(buf); buf=(unsigned char*)b2; headerSz=0;
  1597. } else
  1598. {
  1599. if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) headerSz=3;
  1600. }
  1601. }
  1602. #endif
  1603. if (!buf) { if (pResults) pResults->error=eXMLErrorCharConversionError; return emptyXMLNode; }
  1604. XMLNode x=parseString((XMLSTR)(buf+headerSz),tag,pResults);
  1605. free(buf);
  1606. return x;
  1607. }
  1608. static inline void charmemset(XMLSTR dest,XMLCHAR c,int l) { while (l--) *(dest++)=c; }
  1609. // private:
  1610. // Creates an user friendly XML string from a given element with
  1611. // appropriate white space and carriage returns.
  1612. //
  1613. // This recurses through all subnodes then adds contents of the nodes to the
  1614. // string.
  1615. int XMLNode::CreateXMLStringR(XMLNodeData *pEntry, XMLSTR lpszMarker, int nFormat)
  1616. {
  1617. int nResult = 0;
  1618. int cb=nFormat<0?0:nFormat;
  1619. int cbElement;
  1620. int nChildFormat=-1;
  1621. int nElementI=pEntry->nChild+pEntry->nText+pEntry->nClear;
  1622. int i,j;
  1623. if ((nFormat>=0)&&(nElementI==1)&&(pEntry->nText==1)&&(!pEntry->isDeclaration)) nFormat=-2;
  1624. assert(pEntry);
  1625. #define LENSTR(lpsz) (lpsz ? xstrlen(lpsz) : 0)
  1626. // If the element has no name then assume this is the head node.
  1627. cbElement = (int)LENSTR(pEntry->lpszName);
  1628. if (cbElement)
  1629. {
  1630. // "<elementname "
  1631. if (lpszMarker)
  1632. {
  1633. if (cb) charmemset(lpszMarker, INDENTCHAR, cb);
  1634. nResult = cb;
  1635. lpszMarker[nResult++]=_CXML('<');
  1636. if (pEntry->isDeclaration) lpszMarker[nResult++]=_CXML('?');
  1637. xstrcpy(&lpszMarker[nResult], pEntry->lpszName);
  1638. nResult+=cbElement;
  1639. lpszMarker[nResult++]=_CXML(' ');
  1640. } else
  1641. {
  1642. nResult+=cbElement+2+cb;
  1643. if (pEntry->isDeclaration) nResult++;
  1644. }
  1645. // Enumerate attributes and add them to the string
  1646. XMLAttribute *pAttr=pEntry->pAttribute;
  1647. for (i=0; i<pEntry->nAttribute; i++)
  1648. {
  1649. // "Attrib
  1650. cb = (int)LENSTR(pAttr->lpszName);
  1651. if (cb)
  1652. {
  1653. if (lpszMarker) xstrcpy(&lpszMarker[nResult], pAttr->lpszName);
  1654. nResult += cb;
  1655. // "Attrib=Value "
  1656. if (pAttr->lpszValue)
  1657. {
  1658. cb=(int)ToXMLStringTool::lengthXMLString(pAttr->lpszValue);
  1659. if (lpszMarker)
  1660. {
  1661. lpszMarker[nResult]=_CXML('=');
  1662. lpszMarker[nResult+1]=_CXML('"');
  1663. if (cb) ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult+2],pAttr->lpszValue);
  1664. lpszMarker[nResult+cb+2]=_CXML('"');
  1665. }
  1666. nResult+=cb+3;
  1667. }
  1668. if (lpszMarker) lpszMarker[nResult] = _CXML(' ');
  1669. nResult++;
  1670. }
  1671. pAttr++;
  1672. }
  1673. if (pEntry->isDeclaration)
  1674. {
  1675. if (lpszMarker)
  1676. {
  1677. lpszMarker[nResult-1]=_CXML('?');
  1678. lpszMarker[nResult]=_CXML('>');
  1679. }
  1680. nResult++;
  1681. if (nFormat!=-1)
  1682. {
  1683. if (lpszMarker) lpszMarker[nResult]=_CXML('\n');
  1684. nResult++;
  1685. }
  1686. } else
  1687. // If there are child nodes we need to terminate the start tag
  1688. if (nElementI)
  1689. {
  1690. if (lpszMarker) lpszMarker[nResult-1]=_CXML('>');
  1691. if (nFormat>=0)
  1692. {
  1693. if (lpszMarker) lpszMarker[nResult]=_CXML('\n');
  1694. nResult++;
  1695. }
  1696. } else nResult--;
  1697. }
  1698. // Calculate the child format for when we recurse. This is used to
  1699. // determine the number of spaces used for prefixes.
  1700. if (nFormat!=-1)
  1701. {
  1702. if (cbElement&&(!pEntry->isDeclaration)) nChildFormat=nFormat+1;
  1703. else nChildFormat=nFormat;
  1704. }
  1705. // Enumerate through remaining children
  1706. for (i=0; i<nElementI; i++)
  1707. {
  1708. j=pEntry->pOrder[i];
  1709. switch((XMLElementType)(j&3))
  1710. {
  1711. // Text nodes
  1712. case eNodeText:
  1713. {
  1714. // "Text"
  1715. XMLCSTR pChild=pEntry->pText[j>>2];
  1716. cb = (int)ToXMLStringTool::lengthXMLString(pChild);
  1717. if (cb)
  1718. {
  1719. if (nFormat>=0)
  1720. {
  1721. if (lpszMarker)
  1722. {
  1723. charmemset(&lpszMarker[nResult],INDENTCHAR,nFormat+1);
  1724. ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult+nFormat+1],pChild);
  1725. lpszMarker[nResult+nFormat+1+cb]=_CXML('\n');
  1726. }
  1727. nResult+=cb+nFormat+2;
  1728. } else
  1729. {
  1730. if (lpszMarker) ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult], pChild);
  1731. nResult += cb;
  1732. }
  1733. }
  1734. break;
  1735. }
  1736. // Clear type nodes
  1737. case eNodeClear:
  1738. {
  1739. XMLClear *pChild=pEntry->pClear+(j>>2);
  1740. // "OpenTag"
  1741. cb = (int)LENSTR(pChild->lpszOpenTag);
  1742. if (cb)
  1743. {
  1744. if (nFormat!=-1)
  1745. {
  1746. if (lpszMarker)
  1747. {
  1748. charmemset(&lpszMarker[nResult], INDENTCHAR, nFormat+1);
  1749. xstrcpy(&lpszMarker[nResult+nFormat+1], pChild->lpszOpenTag);
  1750. }
  1751. nResult+=cb+nFormat+1;
  1752. }
  1753. else
  1754. {
  1755. if (lpszMarker)xstrcpy(&lpszMarker[nResult], pChild->lpszOpenTag);
  1756. nResult += cb;
  1757. }
  1758. }
  1759. // "OpenTag Value"
  1760. cb = (int)LENSTR(pChild->lpszValue);
  1761. if (cb)
  1762. {
  1763. if (lpszMarker) xstrcpy(&lpszMarker[nResult], pChild->lpszValue);
  1764. nResult += cb;
  1765. }
  1766. // "OpenTag Value CloseTag"
  1767. cb = (int)LENSTR(pChild->lpszCloseTag);
  1768. if (cb)
  1769. {
  1770. if (lpszMarker) xstrcpy(&lpszMarker[nResult], pChild->lpszCloseTag);
  1771. nResult += cb;
  1772. }
  1773. if (nFormat!=-1)
  1774. {
  1775. if (lpszMarker) lpszMarker[nResult] = _CXML('\n');
  1776. nResult++;
  1777. }
  1778. break;
  1779. }
  1780. // Element nodes
  1781. case eNodeChild:
  1782. {
  1783. // Recursively add child nodes
  1784. nResult += CreateXMLStringR(pEntry->pChild[j>>2].d, lpszMarker ? lpszMarker + nResult : 0, nChildFormat);
  1785. break;
  1786. }
  1787. default: break;
  1788. }
  1789. }
  1790. if ((cbElement)&&(!pEntry->isDeclaration))
  1791. {
  1792. // If we have child entries we need to use long XML notation for
  1793. // closing the element - "<elementname>blah blah blah</elementname>"
  1794. if (nElementI)
  1795. {
  1796. // "</elementname>\0"
  1797. if (lpszMarker)
  1798. {
  1799. if (nFormat >=0)
  1800. {
  1801. charmemset(&lpszMarker[nResult], INDENTCHAR,nFormat);
  1802. nResult+=nFormat;
  1803. }
  1804. lpszMarker[nResult]=_CXML('<'); lpszMarker[nResult+1]=_CXML('/');
  1805. nResult += 2;
  1806. xstrcpy(&lpszMarker[nResult], pEntry->lpszName);
  1807. nResult += cbElement;
  1808. lpszMarker[nResult]=_CXML('>');
  1809. if (nFormat == -1) nResult++;
  1810. else
  1811. {
  1812. lpszMarker[nResult+1]=_CXML('\n');
  1813. nResult+=2;
  1814. }
  1815. } else
  1816. {
  1817. if (nFormat>=0) nResult+=cbElement+4+nFormat;
  1818. else if (nFormat==-1) nResult+=cbElement+3;
  1819. else nResult+=cbElement+4;
  1820. }
  1821. } else
  1822. {
  1823. // If there are no children we can use shorthand XML notation -
  1824. // "<elementname/>"
  1825. // "/>\0"
  1826. if (lpszMarker)
  1827. {
  1828. lpszMarker[nResult]=_CXML('/'); lpszMarker[nResult+1]=_CXML('>');
  1829. if (nFormat != -1) lpszMarker[nResult+2]=_CXML('\n');
  1830. }
  1831. nResult += nFormat == -1 ? 2 : 3;
  1832. }
  1833. }
  1834. return nResult;
  1835. }
  1836. #undef LENSTR
  1837. // Create an XML string
  1838. // @param int nFormat - 0 if no formatting is required
  1839. // otherwise nonzero for formatted text
  1840. // with carriage returns and indentation.
  1841. // @param int *pnSize - [out] pointer to the size of the
  1842. // returned string not including the
  1843. // NULL terminator.
  1844. // @return XMLSTR - Allocated XML string, you must free
  1845. // this with free().
  1846. XMLSTR XMLNode::createXMLString(int nFormat, int *pnSize) const
  1847. {
  1848. if (!d) { if (pnSize) *pnSize=0; return NULL; }
  1849. XMLSTR lpszResult = NULL;
  1850. int cbStr;
  1851. // Recursively Calculate the size of the XML string
  1852. if (!dropWhiteSpace) nFormat=0;
  1853. nFormat = nFormat ? 0 : -1;
  1854. cbStr = CreateXMLStringR(d, 0, nFormat);
  1855. // Alllocate memory for the XML string + the NULL terminator and
  1856. // create the recursively XML string.
  1857. lpszResult=(XMLSTR)malloc((cbStr+1)*sizeof(XMLCHAR));
  1858. CreateXMLStringR(d, lpszResult, nFormat);
  1859. lpszResult[cbStr]=_CXML('\0');
  1860. if (pnSize) *pnSize = cbStr;
  1861. return lpszResult;
  1862. }
  1863. int XMLNode::detachFromParent(XMLNodeData *d)
  1864. {
  1865. XMLNode *pa=d->pParent->pChild;
  1866. int i=0;
  1867. while (((void*)(pa[i].d))!=((void*)d)) i++;
  1868. d->pParent->nChild--;
  1869. if (d->pParent->nChild) memmove(pa+i,pa+i+1,(d->pParent->nChild-i)*sizeof(XMLNode));
  1870. else { free(pa); d->pParent->pChild=NULL; }
  1871. return removeOrderElement(d->pParent,eNodeChild,i);
  1872. }
  1873. XMLNode::~XMLNode()
  1874. {
  1875. if (!d) return;
  1876. d->ref_count--;
  1877. emptyTheNode(0);
  1878. }
  1879. void XMLNode::deleteNodeContent()
  1880. {
  1881. if (!d) return;
  1882. if (d->pParent) { detachFromParent(d); d->pParent=NULL; d->ref_count--; }
  1883. emptyTheNode(1);
  1884. }
  1885. void XMLNode::emptyTheNode(char force)
  1886. {
  1887. XMLNodeData *dd=d; // warning: must stay this way!
  1888. if ((dd->ref_count==0)||force)
  1889. {
  1890. if (d->pParent) detachFromParent(d);
  1891. int i;
  1892. XMLNode *pc;
  1893. for(i=0; i<dd->nChild; i++)
  1894. {
  1895. pc=dd->pChild+i;
  1896. pc->d->pParent=NULL;
  1897. pc->d->ref_count--;
  1898. pc->emptyTheNode(force);
  1899. }
  1900. myFree(dd->pChild);
  1901. for(i=0; i<dd->nText; i++) free((void*)dd->pText[i]);
  1902. myFree(dd->pText);
  1903. for(i=0; i<dd->nClear; i++) free((void*)dd->pClear[i].lpszValue);
  1904. myFree(dd->pClear);
  1905. for(i=0; i<dd->nAttribute; i++)
  1906. {
  1907. free((void*)dd->pAttribute[i].lpszName);
  1908. if (dd->pAttribute[i].lpszValue) free((void*)dd->pAttribute[i].lpszValue);
  1909. }
  1910. myFree(dd->pAttribute);
  1911. myFree(dd->pOrder);
  1912. myFree((void*)dd->lpszName);
  1913. dd->nChild=0; dd->nText=0; dd->nClear=0; dd->nAttribute=0;
  1914. dd->pChild=NULL; dd->pText=NULL; dd->pClear=NULL; dd->pAttribute=NULL;
  1915. dd->pOrder=NULL; dd->lpszName=NULL; dd->pParent=NULL;
  1916. }
  1917. if (dd->ref_count==0)
  1918. {
  1919. free(dd);
  1920. d=NULL;
  1921. }
  1922. }
  1923. XMLNode& XMLNode::operator=( const XMLNode& A )
  1924. {
  1925. // shallow copy
  1926. if (this != &A)
  1927. {
  1928. if (d) { d->ref_count--; emptyTheNode(0); }
  1929. d=A.d;
  1930. if (d) (d->ref_count) ++ ;
  1931. }
  1932. return *this;
  1933. }
  1934. XMLNode::XMLNode(const XMLNode &A)
  1935. {
  1936. // shallow copy
  1937. d=A.d;
  1938. if (d) (d->ref_count)++ ;
  1939. }
  1940. XMLNode XMLNode::deepCopy() const
  1941. {
  1942. if (!d) return XMLNode::emptyXMLNode;
  1943. XMLNode x(NULL,stringDup(d->lpszName),d->isDeclaration);
  1944. XMLNodeData *p=x.d;
  1945. int n=d->nAttribute;
  1946. if (n)
  1947. {
  1948. p->nAttribute=n; p->pAttribute=(XMLAttribute*)malloc(n*sizeof(XMLAttribute));
  1949. while (n--)
  1950. {
  1951. p->pAttribute[n].lpszName=stringDup(d->pAttribute[n].lpszName);
  1952. p->pAttribute[n].lpszValue=stringDup(d->pAttribute[n].lpszValue);
  1953. }
  1954. }
  1955. if (d->pOrder)
  1956. {
  1957. n=(d->nChild+d->nText+d->nClear)*sizeof(int); p->pOrder=(int*)malloc(n); memcpy(p->pOrder,d->pOrder,n);
  1958. }
  1959. n=d->nText;
  1960. if (n)
  1961. {
  1962. p->nText=n; p->pText=(XMLCSTR*)malloc(n*sizeof(XMLCSTR));
  1963. while(n--) p->pText[n]=stringDup(d->pText[n]);
  1964. }
  1965. n=d->nClear;
  1966. if (n)
  1967. {
  1968. p->nClear=n; p->pClear=(XMLClear*)malloc(n*sizeof(XMLClear));
  1969. while (n--)
  1970. {
  1971. p->pClear[n].lpszCloseTag=d->pClear[n].lpszCloseTag;
  1972. p->pClear[n].lpszOpenTag=d->pClear[n].lpszOpenTag;
  1973. p->pClear[n].lpszValue=stringDup(d->pClear[n].lpszValue);
  1974. }
  1975. }
  1976. n=d->nChild;
  1977. if (n)
  1978. {
  1979. p->nChild=n; p->pChild=(XMLNode*)malloc(n*sizeof(XMLNode));
  1980. while (n--)
  1981. {
  1982. p->pChild[n].d=NULL;
  1983. p->pChild[n]=d->pChild[n].deepCopy();
  1984. p->pChild[n].d->pParent=p;
  1985. }
  1986. }
  1987. return x;
  1988. }
  1989. XMLNode XMLNode::addChild(XMLNode childNode, int pos)
  1990. {
  1991. XMLNodeData *dc=childNode.d;
  1992. if ((!dc)||(!d)) return childNode;
  1993. if (!dc->lpszName)
  1994. {
  1995. // this is a root node: todo: correct fix
  1996. int j=pos;
  1997. while (dc->nChild)
  1998. {
  1999. addChild(dc->pChild[0],j);
  2000. if (pos>=0) j++;
  2001. }
  2002. return childNode;
  2003. }
  2004. if (dc->pParent) { if ((detachFromParent(dc)<=pos)&&(dc->pParent==d)) pos--; } else dc->ref_count++;
  2005. dc->pParent=d;
  2006. // int nc=d->nChild;
  2007. // d->pChild=(XMLNode*)myRealloc(d->pChild,(nc+1),memoryIncrease,sizeof(XMLNode));
  2008. d->pChild=(XMLNode*)addToOrder(0,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
  2009. d->pChild[pos].d=dc;
  2010. d->nChild++;
  2011. return childNode;
  2012. }
  2013. void XMLNode::deleteAttribute(int i)
  2014. {
  2015. if ((!d)||(i<0)||(i>=d->nAttribute)) return;
  2016. d->nAttribute--;
  2017. XMLAttribute *p=d->pAttribute+i;
  2018. free((void*)p->lpszName);
  2019. if (p->lpszValue) free((void*)p->lpszValue);
  2020. if (d->nAttribute) memmove(p,p+1,(d->nAttribute-i)*sizeof(XMLAttribute)); else { free(p); d->pAttribute=NULL; }
  2021. }
  2022. void XMLNode::deleteAttribute(XMLAttribute *a){ if (a) deleteAttribute(a->lpszName); }
  2023. void XMLNode::deleteAttribute(XMLCSTR lpszName)
  2024. {
  2025. int j=0;
  2026. getAttribute(lpszName,&j);
  2027. if (j) deleteAttribute(j-1);
  2028. }
  2029. XMLAttribute *XMLNode::updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName,int i)
  2030. {
  2031. if (!d) { if (lpszNewValue) free(lpszNewValue); if (lpszNewName) free(lpszNewName); return NULL; }
  2032. if (i>=d->nAttribute)
  2033. {
  2034. if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
  2035. return NULL;
  2036. }
  2037. XMLAttribute *p=d->pAttribute+i;
  2038. if (p->lpszValue&&p->lpszValue!=lpszNewValue) free((void*)p->lpszValue);
  2039. p->lpszValue=lpszNewValue;
  2040. if (lpszNewName&&p->lpszName!=lpszNewName) { free((void*)p->lpszName); p->lpszName=lpszNewName; };
  2041. return p;
  2042. }
  2043. XMLAttribute *XMLNode::updateAttribute_WOSD(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
  2044. {
  2045. if (oldAttribute) return updateAttribute_WOSD((XMLSTR)newAttribute->lpszValue,(XMLSTR)newAttribute->lpszName,oldAttribute->lpszName);
  2046. return addAttribute_WOSD((XMLSTR)newAttribute->lpszName,(XMLSTR)newAttribute->lpszValue);
  2047. }
  2048. XMLAttribute *XMLNode::updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName,XMLCSTR lpszOldName)
  2049. {
  2050. int j=0;
  2051. getAttribute(lpszOldName,&j);
  2052. if (j) return updateAttribute_WOSD(lpszNewValue,lpszNewName,j-1);
  2053. else
  2054. {
  2055. if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
  2056. else return addAttribute_WOSD(stringDup(lpszOldName),lpszNewValue);
  2057. }
  2058. }
  2059. int XMLNode::indexText(XMLCSTR lpszValue) const
  2060. {
  2061. if (!d) return -1;
  2062. int i,l=d->nText;
  2063. if (!lpszValue) { if (l) return 0; return -1; }
  2064. XMLCSTR *p=d->pText;
  2065. for (i=0; i<l; i++) if (lpszValue==p[i]) return i;
  2066. return -1;
  2067. }
  2068. void XMLNode::deleteText(int i)
  2069. {
  2070. if ((!d)||(i<0)||(i>=d->nText)) return;
  2071. d->nText--;
  2072. XMLCSTR *p=d->pText+i;
  2073. free((void*)*p);
  2074. if (d->nText) memmove(p,p+1,(d->nText-i)*sizeof(XMLCSTR)); else { free(p); d->pText=NULL; }
  2075. removeOrderElement(d,eNodeText,i);
  2076. }
  2077. void XMLNode::deleteText(XMLCSTR lpszValue) { deleteText(indexText(lpszValue)); }
  2078. XMLCSTR XMLNode::updateText_WOSD(XMLSTR lpszNewValue, int i)
  2079. {
  2080. if (!d) { if (lpszNewValue) free(lpszNewValue); return NULL; }
  2081. if (i>=d->nText) return addText_WOSD(lpszNewValue);
  2082. XMLCSTR *p=d->pText+i;
  2083. if (*p!=lpszNewValue) { free((void*)*p); *p=lpszNewValue; }
  2084. return lpszNewValue;
  2085. }
  2086. XMLCSTR XMLNode::updateText_WOSD(XMLSTR lpszNewValue, XMLCSTR lpszOldValue)
  2087. {
  2088. if (!d) { if (lpszNewValue) free(lpszNewValue); return NULL; }
  2089. int i=indexText(lpszOldValue);
  2090. if (i>=0) return updateText_WOSD(lpszNewValue,i);
  2091. return addText_WOSD(lpszNewValue);
  2092. }
  2093. void XMLNode::deleteClear(int i)
  2094. {
  2095. if ((!d)||(i<0)||(i>=d->nClear)) return;
  2096. d->nClear--;
  2097. XMLClear *p=d->pClear+i;
  2098. free((void*)p->lpszValue);
  2099. if (d->nClear) memmove(p,p+1,(d->nClear-i)*sizeof(XMLClear)); else { free(p); d->pClear=NULL; }
  2100. removeOrderElement(d,eNodeClear,i);
  2101. }
  2102. int XMLNode::indexClear(XMLCSTR lpszValue) const
  2103. {
  2104. if (!d) return -1;
  2105. int i,l=d->nClear;
  2106. if (!lpszValue) { if (l) return 0; return -1; }
  2107. XMLClear *p=d->pClear;
  2108. for (i=0; i<l; i++) if (lpszValue==p[i].lpszValue) return i;
  2109. return -1;
  2110. }
  2111. void XMLNode::deleteClear(XMLCSTR lpszValue) { deleteClear(indexClear(lpszValue)); }
  2112. void XMLNode::deleteClear(XMLClear *a) { if (a) deleteClear(a->lpszValue); }
  2113. XMLClear *XMLNode::updateClear_WOSD(XMLSTR lpszNewContent, int i)
  2114. {
  2115. if (!d) { if (lpszNewContent) free(lpszNewContent); return NULL; }
  2116. if (i>=d->nClear) return addClear_WOSD(lpszNewContent);
  2117. XMLClear *p=d->pClear+i;
  2118. if (lpszNewContent!=p->lpszValue) { free((void*)p->lpszValue); p->lpszValue=lpszNewContent; }
  2119. return p;
  2120. }
  2121. XMLClear *XMLNode::updateClear_WOSD(XMLSTR lpszNewContent, XMLCSTR lpszOldValue)
  2122. {
  2123. if (!d) { if (lpszNewContent) free(lpszNewContent); return NULL; }
  2124. int i=indexClear(lpszOldValue);
  2125. if (i>=0) return updateClear_WOSD(lpszNewContent,i);
  2126. return addClear_WOSD(lpszNewContent);
  2127. }
  2128. XMLClear *XMLNode::updateClear_WOSD(XMLClear *newP,XMLClear *oldP)
  2129. {
  2130. if (oldP) return updateClear_WOSD((XMLSTR)newP->lpszValue,(XMLSTR)oldP->lpszValue);
  2131. return NULL;
  2132. }
  2133. int XMLNode::nChildNode(XMLCSTR name) const
  2134. {
  2135. if (!d) return 0;
  2136. int i,j=0,n=d->nChild;
  2137. XMLNode *pc=d->pChild;
  2138. for (i=0; i<n; i++)
  2139. {
  2140. if (xstricmp(pc->d->lpszName, name)==0) j++;
  2141. pc++;
  2142. }
  2143. return j;
  2144. }
  2145. XMLNode XMLNode::getChildNode(XMLCSTR name, int *j) const
  2146. {
  2147. if (!d) return emptyXMLNode;
  2148. int i=0,n=d->nChild;
  2149. if (j) i=*j;
  2150. XMLNode *pc=d->pChild+i;
  2151. for (; i<n; i++)
  2152. {
  2153. if (!xstricmp(pc->d->lpszName, name))
  2154. {
  2155. if (j) *j=i+1;
  2156. return *pc;
  2157. }
  2158. pc++;
  2159. }
  2160. return emptyXMLNode;
  2161. }
  2162. XMLNode XMLNode::getChildNode(XMLCSTR name, int j) const
  2163. {
  2164. if (!d) return emptyXMLNode;
  2165. if (j>=0)
  2166. {
  2167. int i=0;
  2168. while (j-->0) getChildNode(name,&i);
  2169. return getChildNode(name,&i);
  2170. }
  2171. int i=d->nChild;
  2172. while (i--) if (!xstricmp(name,d->pChild[i].d->lpszName)) break;
  2173. if (i<0) return emptyXMLNode;
  2174. return getChildNode(i);
  2175. }
  2176. XMLNode XMLNode::getChildNodeByPath(XMLCSTR _path, char createMissing, XMLCHAR sep)
  2177. {
  2178. XMLSTR path=stringDup(_path);
  2179. XMLNode x=getChildNodeByPath(path,createMissing,sep);
  2180. if (path) free(path);
  2181. return x;
  2182. }
  2183. XMLNode XMLNode::getChildNodeByPath(XMLSTR path, char createIfMissing, XMLCHAR sep)
  2184. {
  2185. if ((!path)||(!(*path))) return *this;
  2186. XMLNode xn,xbase=*this;
  2187. XMLCHAR *tend1,sepString[2]; sepString[0]=sep; sepString[1]=0;
  2188. tend1=xstrstr(path,sepString);
  2189. while(tend1)
  2190. {
  2191. *tend1=0;
  2192. xn=xbase.getChildNode(path);
  2193. if (xn.isEmpty())
  2194. {
  2195. if (createIfMissing) xn=xbase.addChild(path);
  2196. else return XMLNode::emptyXMLNode;
  2197. }
  2198. xbase=xn;
  2199. path=tend1+1;
  2200. tend1=xstrstr(path,sepString);
  2201. }
  2202. xn=xbase.getChildNode(path);
  2203. if (xn.isEmpty()&&createIfMissing) xn=xbase.addChild(path);
  2204. return xn;
  2205. }
  2206. XMLElementPosition XMLNode::positionOfText (int i) const { if (i>=d->nText ) i=d->nText-1; return findPosition(d,i,eNodeText ); }
  2207. XMLElementPosition XMLNode::positionOfClear (int i) const { if (i>=d->nClear) i=d->nClear-1; return findPosition(d,i,eNodeClear); }
  2208. XMLElementPosition XMLNode::positionOfChildNode(int i) const { if (i>=d->nChild) i=d->nChild-1; return findPosition(d,i,eNodeChild); }
  2209. XMLElementPosition XMLNode::positionOfText (XMLCSTR lpszValue) const { return positionOfText (indexText (lpszValue)); }
  2210. XMLElementPosition XMLNode::positionOfClear(XMLCSTR lpszValue) const { return positionOfClear(indexClear(lpszValue)); }
  2211. XMLElementPosition XMLNode::positionOfClear(XMLClear *a) const { if (a) return positionOfClear(a->lpszValue); return positionOfClear(); }
  2212. XMLElementPosition XMLNode::positionOfChildNode(XMLNode x) const
  2213. {
  2214. if ((!d)||(!x.d)) return -1;
  2215. XMLNodeData *dd=x.d;
  2216. XMLNode *pc=d->pChild;
  2217. int i=d->nChild;
  2218. while (i--) if (pc[i].d==dd) return findPosition(d,i,eNodeChild);
  2219. return -1;
  2220. }
  2221. XMLElementPosition XMLNode::positionOfChildNode(XMLCSTR name, int count) const
  2222. {
  2223. if (!name) return positionOfChildNode(count);
  2224. int j=0;
  2225. do { getChildNode(name,&j); if (j<0) return -1; } while (count--);
  2226. return findPosition(d,j-1,eNodeChild);
  2227. }
  2228. XMLNode XMLNode::getChildNodeWithAttribute(XMLCSTR name,XMLCSTR attributeName,XMLCSTR attributeValue, int *k) const
  2229. {
  2230. int i=0,j;
  2231. if (k) i=*k;
  2232. XMLNode x;
  2233. XMLCSTR t;
  2234. do
  2235. {
  2236. x=getChildNode(name,&i);
  2237. if (!x.isEmpty())
  2238. {
  2239. if (attributeValue)
  2240. {
  2241. j=0;
  2242. do
  2243. {
  2244. t=x.getAttribute(attributeName,&j);
  2245. if (t&&(xstricmp(attributeValue,t)==0)) { if (k) *k=i; return x; }
  2246. } while (t);
  2247. } else
  2248. {
  2249. if (x.isAttributeSet(attributeName)) { if (k) *k=i; return x; }
  2250. }
  2251. }
  2252. } while (!x.isEmpty());
  2253. return emptyXMLNode;
  2254. }
  2255. // Find an attribute on an node.
  2256. XMLCSTR XMLNode::getAttribute(XMLCSTR lpszAttrib, int *j) const
  2257. {
  2258. if (!d) return NULL;
  2259. int i=0,n=d->nAttribute;
  2260. if (j) i=*j;
  2261. XMLAttribute *pAttr=d->pAttribute+i;
  2262. for (; i<n; i++)
  2263. {
  2264. if (xstricmp(pAttr->lpszName, lpszAttrib)==0)
  2265. {
  2266. if (j) *j=i+1;
  2267. return pAttr->lpszValue;
  2268. }
  2269. pAttr++;
  2270. }
  2271. return NULL;
  2272. }
  2273. char XMLNode::isAttributeSet(XMLCSTR lpszAttrib) const
  2274. {
  2275. if (!d) return FALSE;
  2276. int i,n=d->nAttribute;
  2277. XMLAttribute *pAttr=d->pAttribute;
  2278. for (i=0; i<n; i++)
  2279. {
  2280. if (xstricmp(pAttr->lpszName, lpszAttrib)==0)
  2281. {
  2282. return TRUE;
  2283. }
  2284. pAttr++;
  2285. }
  2286. return FALSE;
  2287. }
  2288. XMLCSTR XMLNode::getAttribute(XMLCSTR name, int j) const
  2289. {
  2290. if (!d) return NULL;
  2291. int i=0;
  2292. while (j-->0) getAttribute(name,&i);
  2293. return getAttribute(name,&i);
  2294. }
  2295. XMLNodeContents XMLNode::enumContents(int i) const
  2296. {
  2297. XMLNodeContents c;
  2298. if (!d) { c.etype=eNodeNULL; return c; }
  2299. if (i<d->nAttribute)
  2300. {
  2301. c.etype=eNodeAttribute;
  2302. c.attrib=d->pAttribute[i];
  2303. return c;
  2304. }
  2305. i-=d->nAttribute;
  2306. c.etype=(XMLElementType)(d->pOrder[i]&3);
  2307. i=(d->pOrder[i])>>2;
  2308. switch (c.etype)
  2309. {
  2310. case eNodeChild: c.child = d->pChild[i]; break;
  2311. case eNodeText: c.text = d->pText[i]; break;
  2312. case eNodeClear: c.clear = d->pClear[i]; break;
  2313. default: break;
  2314. }
  2315. return c;
  2316. }
  2317. XMLCSTR XMLNode::getName() const { if (!d) return NULL; return d->lpszName; }
  2318. int XMLNode::nText() const { if (!d) return 0; return d->nText; }
  2319. int XMLNode::nChildNode() const { if (!d) return 0; return d->nChild; }
  2320. int XMLNode::nAttribute() const { if (!d) return 0; return d->nAttribute; }
  2321. int XMLNode::nClear() const { if (!d) return 0; return d->nClear; }
  2322. int XMLNode::nElement() const { if (!d) return 0; return d->nAttribute+d->nChild+d->nText+d->nClear; }
  2323. XMLClear XMLNode::getClear (int i) const { if ((!d)||(i>=d->nClear )) return emptyXMLClear; return d->pClear[i]; }
  2324. XMLAttribute XMLNode::getAttribute (int i) const { if ((!d)||(i>=d->nAttribute)) return emptyXMLAttribute; return d->pAttribute[i]; }
  2325. XMLCSTR XMLNode::getAttributeName (int i) const { if ((!d)||(i>=d->nAttribute)) return NULL; return d->pAttribute[i].lpszName; }
  2326. XMLCSTR XMLNode::getAttributeValue(int i) const { if ((!d)||(i>=d->nAttribute)) return NULL; return d->pAttribute[i].lpszValue; }
  2327. XMLCSTR XMLNode::getText (int i) const { if ((!d)||(i>=d->nText )) return NULL; return d->pText[i]; }
  2328. XMLNode XMLNode::getChildNode (int i) const { if ((!d)||(i>=d->nChild )) return emptyXMLNode; return d->pChild[i]; }
  2329. XMLNode XMLNode::getParentNode ( ) const { if ((!d)||(!d->pParent )) return emptyXMLNode; return XMLNode(d->pParent); }
  2330. char XMLNode::isDeclaration ( ) const { if (!d) return 0; return d->isDeclaration; }
  2331. char XMLNode::isEmpty ( ) const { return (d==NULL); }
  2332. XMLNode XMLNode::emptyNode ( ) { return XMLNode::emptyXMLNode; }
  2333. XMLNode XMLNode::addChild(XMLCSTR lpszName, char isDeclaration, XMLElementPosition pos)
  2334. { return addChild_priv(0,stringDup(lpszName),isDeclaration,pos); }
  2335. XMLNode XMLNode::addChild_WOSD(XMLSTR lpszName, char isDeclaration, XMLElementPosition pos)
  2336. { return addChild_priv(0,lpszName,isDeclaration,pos); }
  2337. XMLAttribute *XMLNode::addAttribute(XMLCSTR lpszName, XMLCSTR lpszValue)
  2338. { return addAttribute_priv(0,stringDup(lpszName),stringDup(lpszValue)); }
  2339. XMLAttribute *XMLNode::addAttribute_WOSD(XMLSTR lpszName, XMLSTR lpszValuev)
  2340. { return addAttribute_priv(0,lpszName,lpszValuev); }
  2341. XMLCSTR XMLNode::addText(XMLCSTR lpszValue, XMLElementPosition pos)
  2342. { return addText_priv(0,stringDup(lpszValue),pos); }
  2343. XMLCSTR XMLNode::addText_WOSD(XMLSTR lpszValue, XMLElementPosition pos)
  2344. { return addText_priv(0,lpszValue,pos); }
  2345. XMLClear *XMLNode::addClear(XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, XMLElementPosition pos)
  2346. { return addClear_priv(0,stringDup(lpszValue),lpszOpen,lpszClose,pos); }
  2347. XMLClear *XMLNode::addClear_WOSD(XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, XMLElementPosition pos)
  2348. { return addClear_priv(0,lpszValue,lpszOpen,lpszClose,pos); }
  2349. XMLCSTR XMLNode::updateName(XMLCSTR lpszName)
  2350. { return updateName_WOSD(stringDup(lpszName)); }
  2351. XMLAttribute *XMLNode::updateAttribute(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
  2352. { return updateAttribute_WOSD(stringDup(newAttribute->lpszValue),stringDup(newAttribute->lpszName),oldAttribute->lpszName); }
  2353. XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,int i)
  2354. { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),i); }
  2355. XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,XMLCSTR lpszOldName)
  2356. { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),lpszOldName); }
  2357. XMLCSTR XMLNode::updateText(XMLCSTR lpszNewValue, int i)
  2358. { return updateText_WOSD(stringDup(lpszNewValue),i); }
  2359. XMLCSTR XMLNode::updateText(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
  2360. { return updateText_WOSD(stringDup(lpszNewValue),lpszOldValue); }
  2361. XMLClear *XMLNode::updateClear(XMLCSTR lpszNewContent, int i)
  2362. { return updateClear_WOSD(stringDup(lpszNewContent),i); }
  2363. XMLClear *XMLNode::updateClear(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
  2364. { return updateClear_WOSD(stringDup(lpszNewValue),lpszOldValue); }
  2365. XMLClear *XMLNode::updateClear(XMLClear *newP,XMLClear *oldP)
  2366. { return updateClear_WOSD(stringDup(newP->lpszValue),oldP->lpszValue); }
  2367. char XMLNode::setGlobalOptions(XMLCharEncoding _characterEncoding, char _guessWideCharChars,
  2368. char _dropWhiteSpace, char _removeCommentsInMiddleOfText)
  2369. {
  2370. guessWideCharChars=_guessWideCharChars; dropWhiteSpace=_dropWhiteSpace; removeCommentsInMiddleOfText=_removeCommentsInMiddleOfText;
  2371. #ifdef _XMLWIDECHAR
  2372. if (_characterEncoding) characterEncoding=_characterEncoding;
  2373. #else
  2374. switch(_characterEncoding)
  2375. {
  2376. case char_encoding_UTF8: characterEncoding=_characterEncoding; XML_ByteTable=XML_utf8ByteTable; break;
  2377. case char_encoding_legacy: characterEncoding=_characterEncoding; XML_ByteTable=XML_legacyByteTable; break;
  2378. case char_encoding_ShiftJIS: characterEncoding=_characterEncoding; XML_ByteTable=XML_sjisByteTable; break;
  2379. case char_encoding_GB2312: characterEncoding=_characterEncoding; XML_ByteTable=XML_gb2312ByteTable; break;
  2380. case char_encoding_Big5:
  2381. case char_encoding_GBK: characterEncoding=_characterEncoding; XML_ByteTable=XML_gbk_big5_ByteTable; break;
  2382. default: return 1;
  2383. }
  2384. #endif
  2385. return 0;
  2386. }
  2387. XMLNode::XMLCharEncoding XMLNode::guessCharEncoding(void *buf,int l, char useXMLEncodingAttribute)
  2388. {
  2389. #ifdef _XMLWIDECHAR
  2390. return (XMLCharEncoding)0;
  2391. #else
  2392. if (l<25) return (XMLCharEncoding)0;
  2393. if (guessWideCharChars&&(myIsTextWideChar(buf,l))) return (XMLCharEncoding)0;
  2394. unsigned char *b=(unsigned char*)buf;
  2395. if ((b[0]==0xef)&&(b[1]==0xbb)&&(b[2]==0xbf)) return char_encoding_UTF8;
  2396. // Match utf-8 model ?
  2397. XMLCharEncoding bestGuess=char_encoding_UTF8;
  2398. int i=0;
  2399. while (i<l)
  2400. switch (XML_utf8ByteTable[b[i]])
  2401. {
  2402. case 4: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ?
  2403. case 3: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ?
  2404. case 2: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ?
  2405. case 1: i++; break;
  2406. case 0: i=l;
  2407. }
  2408. if (!useXMLEncodingAttribute) return bestGuess;
  2409. // if encoding is specified and different from utf-8 than it's non-utf8
  2410. // otherwise it's utf-8
  2411. char bb[201];
  2412. l=mmin(l,200);
  2413. memcpy(bb,buf,l); // copy buf into bb to be able to do "bb[l]=0"
  2414. bb[l]=0;
  2415. b=(unsigned char*)strstr(bb,"encoding");
  2416. if (!b) return bestGuess;
  2417. b+=8; while XML_isSPACECHAR(*b) b++; if (*b!='=') return bestGuess;
  2418. b++; while XML_isSPACECHAR(*b) b++; if ((*b!='\'')&&(*b!='"')) return bestGuess;
  2419. b++; while XML_isSPACECHAR(*b) b++;
  2420. if ((xstrnicmp((char*)b,"utf-8",5)==0)||
  2421. (xstrnicmp((char*)b,"utf8",4)==0))
  2422. {
  2423. if (bestGuess==char_encoding_legacy) return char_encoding_error;
  2424. return char_encoding_UTF8;
  2425. }
  2426. if ((xstrnicmp((char*)b,"shiftjis",8)==0)||
  2427. (xstrnicmp((char*)b,"shift-jis",9)==0)||
  2428. (xstrnicmp((char*)b,"sjis",4)==0)) return char_encoding_ShiftJIS;
  2429. if (xstrnicmp((char*)b,"GB2312",6)==0) return char_encoding_GB2312;
  2430. if (xstrnicmp((char*)b,"Big5",4)==0) return char_encoding_Big5;
  2431. if (xstrnicmp((char*)b,"GBK",3)==0) return char_encoding_GBK;
  2432. return char_encoding_legacy;
  2433. #endif
  2434. }
  2435. #undef XML_isSPACECHAR
  2436. //////////////////////////////////////////////////////////
  2437. // Here starts the base64 conversion functions. //
  2438. //////////////////////////////////////////////////////////
  2439. static const char base64Fillchar = _CXML('='); // used to mark partial words at the end
  2440. // this lookup table defines the base64 encoding
  2441. XMLCSTR base64EncodeTable=_CXML("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  2442. // Decode Table gives the index of any valid base64 character in the Base64 table]
  2443. // 96: '=' - 97: space char - 98: illegal char - 99: end of string
  2444. const unsigned char base64DecodeTable[] = {
  2445. 99,98,98,98,98,98,98,98,98,97, 97,98,98,97,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //00 -29
  2446. 98,98,97,98,98,98,98,98,98,98, 98,98,98,62,98,98,98,63,52,53, 54,55,56,57,58,59,60,61,98,98, //30 -59
  2447. 98,96,98,98,98, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, 15,16,17,18,19,20,21,22,23,24, //60 -89
  2448. 25,98,98,98,98,98,98,26,27,28, 29,30,31,32,33,34,35,36,37,38, 39,40,41,42,43,44,45,46,47,48, //90 -119
  2449. 49,50,51,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //120 -149
  2450. 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //150 -179
  2451. 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //180 -209
  2452. 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //210 -239
  2453. 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98 //240 -255
  2454. };
  2455. XMLParserBase64Tool::~XMLParserBase64Tool(){ freeBuffer(); }
  2456. void XMLParserBase64Tool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; }
  2457. int XMLParserBase64Tool::encodeLength(int inlen, char formatted)
  2458. {
  2459. unsigned int i=((inlen-1)/3*4+4+1);
  2460. if (formatted) i+=inlen/54;
  2461. return i;
  2462. }
  2463. XMLSTR XMLParserBase64Tool::encode(unsigned char *inbuf, unsigned int inlen, char formatted)
  2464. {
  2465. int i=encodeLength(inlen,formatted),k=17,eLen=inlen/3,j;
  2466. alloc(i*sizeof(XMLCHAR));
  2467. XMLSTR curr=(XMLSTR)buf;
  2468. for(i=0;i<eLen;i++)
  2469. {
  2470. // Copy next three bytes into lower 24 bits of int, paying attention to sign.
  2471. j=(inbuf[0]<<16)|(inbuf[1]<<8)|inbuf[2]; inbuf+=3;
  2472. // Encode the int into four chars
  2473. *(curr++)=base64EncodeTable[ j>>18 ];
  2474. *(curr++)=base64EncodeTable[(j>>12)&0x3f];
  2475. *(curr++)=base64EncodeTable[(j>> 6)&0x3f];
  2476. *(curr++)=base64EncodeTable[(j )&0x3f];
  2477. if (formatted) { if (!k) { *(curr++)=_CXML('\n'); k=18; } k--; }
  2478. }
  2479. eLen=inlen-eLen*3; // 0 - 2.
  2480. if (eLen==1)
  2481. {
  2482. *(curr++)=base64EncodeTable[ inbuf[0]>>2 ];
  2483. *(curr++)=base64EncodeTable[(inbuf[0]<<4)&0x3F];
  2484. *(curr++)=base64Fillchar;
  2485. *(curr++)=base64Fillchar;
  2486. } else if (eLen==2)
  2487. {
  2488. j=(inbuf[0]<<8)|inbuf[1];
  2489. *(curr++)=base64EncodeTable[ j>>10 ];
  2490. *(curr++)=base64EncodeTable[(j>> 4)&0x3f];
  2491. *(curr++)=base64EncodeTable[(j<< 2)&0x3f];
  2492. *(curr++)=base64Fillchar;
  2493. }
  2494. *(curr++)=0;
  2495. return (XMLSTR)buf;
  2496. }
  2497. unsigned int XMLParserBase64Tool::decodeSize(XMLCSTR data,XMLError *xe)
  2498. {
  2499. if (xe) *xe=eXMLErrorNone;
  2500. int size=0;
  2501. unsigned char c;
  2502. //skip any extra characters (e.g. newlines or spaces)
  2503. while (*data)
  2504. {
  2505. #ifdef _XMLWIDECHAR
  2506. if (*data>255) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
  2507. #endif
  2508. c=base64DecodeTable[(unsigned char)(*data)];
  2509. if (c<97) size++;
  2510. else if (c==98) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
  2511. data++;
  2512. }
  2513. if (xe&&(size%4!=0)) *xe=eXMLErrorBase64DataSizeIsNotMultipleOf4;
  2514. if (size==0) return 0;
  2515. do { data--; size--; } while(*data==base64Fillchar); size++;
  2516. return (unsigned int)((size*3)/4);
  2517. }
  2518. unsigned char XMLParserBase64Tool::decode(XMLCSTR data, unsigned char *buf, int len, XMLError *xe)
  2519. {
  2520. if (xe) *xe=eXMLErrorNone;
  2521. int i=0,p=0;
  2522. unsigned char d,c;
  2523. for(;;)
  2524. {
  2525. #ifdef _XMLWIDECHAR
  2526. #define BASE64DECODE_READ_NEXT_CHAR(c) \
  2527. do { \
  2528. if (data[i]>255){ c=98; break; } \
  2529. c=base64DecodeTable[(unsigned char)data[i++]]; \
  2530. }while (c==97); \
  2531. if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
  2532. #else
  2533. #define BASE64DECODE_READ_NEXT_CHAR(c) \
  2534. do { c=base64DecodeTable[(unsigned char)data[i++]]; }while (c==97); \
  2535. if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
  2536. #endif
  2537. BASE64DECODE_READ_NEXT_CHAR(c)
  2538. if (c==99) { return 2; }
  2539. if (c==96)
  2540. {
  2541. if (p==(int)len) return 2;
  2542. if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;
  2543. return 1;
  2544. }
  2545. BASE64DECODE_READ_NEXT_CHAR(d)
  2546. if ((d==99)||(d==96)) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; }
  2547. if (p==(int)len) { if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall; return 0; }
  2548. buf[p++]=(unsigned char)((c<<2)|((d>>4)&0x3));
  2549. BASE64DECODE_READ_NEXT_CHAR(c)
  2550. if (c==99) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; }
  2551. if (p==(int)len)
  2552. {
  2553. if (c==96) return 2;
  2554. if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
  2555. return 0;
  2556. }
  2557. if (c==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; }
  2558. buf[p++]=(unsigned char)(((d<<4)&0xf0)|((c>>2)&0xf));
  2559. BASE64DECODE_READ_NEXT_CHAR(d)
  2560. if (d==99 ) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; }
  2561. if (p==(int)len)
  2562. {
  2563. if (d==96) return 2;
  2564. if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
  2565. return 0;
  2566. }
  2567. if (d==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return 1; }
  2568. buf[p++]=(unsigned char)(((c<<6)&0xc0)|d);
  2569. }
  2570. }
  2571. #undef BASE64DECODE_READ_NEXT_CHAR
  2572. void XMLParserBase64Tool::alloc(int newsize)
  2573. {
  2574. if ((!buf)&&(newsize)) { buf=malloc(newsize); buflen=newsize; return; }
  2575. if (newsize>buflen) { buf=realloc(buf,newsize); buflen=newsize; }
  2576. }
  2577. unsigned char *XMLParserBase64Tool::decode(XMLCSTR data, int *outlen, XMLError *xe)
  2578. {
  2579. if (xe) *xe=eXMLErrorNone;
  2580. unsigned int len=decodeSize(data,xe);
  2581. if (outlen) *outlen=len;
  2582. if (!len) return NULL;
  2583. alloc(len+1);
  2584. if(!decode(data,(unsigned char*)buf,len,xe)){ return NULL; }
  2585. return (unsigned char*)buf;
  2586. }