PageRenderTime 71ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/RakNet/DependentExtensions/XML/xmlParser.cpp

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