PageRenderTime 66ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/zeromq/foreign/xmlParser/xmlParser.cpp

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