PageRenderTime 80ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/xmlParser/xmlParser.cpp

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