PageRenderTime 39ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/xmlParser.cpp

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