PageRenderTime 36ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/Horde3D/Source/Shared/utXMLParser.cpp

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